本文介绍JavaScript中通过构造函数定义类属性与方法的封装方式,并结合静态公用方法与prototype原型对象实现属性共享。通过示例展示如何创建实例并调用继承的属性和方法,帮助理解面向对象编程基础。
JavaScript对象封装与原型继承实现
本文通过具体实例解析JavaScript的封装实现方式,旨在为读者提供参考。
var Person = function(name, gender, age) {
this.Name = name;
this.Gender = gender;
this.Age = age;
this.SetName = function(sname) {
this.Name = sname;
}
this.GetName = function() {
return this.Name;
}
this.SetGender = function(sgender) {
this.Gender = sgender;
}
this.GetGender = function() {
return this.Gender;
}
};
/*
静态公用方法
*/
Person.Play = function() {
alert("这是一个静态方法");
}
/*
Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。
这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。
*/
Person.prototype.Address = "中华人民共和国";
Person.prototype.SayHello = function() {
alert(Person.prototype.Address);
}
希望上述内容能对读者的JavaScript程序设计工作提供有益帮助。