87,909
社区成员
发帖
与我相关
我的任务
分享
function Person() {
this._name;
}
Person.prototype = {
constructor: Person,
get name() {return this._name;},
set name(value) {this._name = value;}
}
function Person() {
this._name;
}
Person.prototype.get name = function() {return this._name;};
Person.prototype.set name = function(value) {this._name = value;};
this._name;
替换成var _name;
以实现模拟私有变量的效果呢(只对外开放公有访问方法)?把上述代码改写成这样——(然而经测试得知下面这样是不行的:给对象的一个实例设置属性值后,所有实例都将得到相同的属性值,而不是各自具有不同的属性值)
function Person() {
var _name;
if (typeof this.getName != "function") {
Person.prototype.getName = function() {return _name;};
Person.prototype.setName = function(value) {_name = value;};
}
}