我正在尝试学习get和设置JavaScript对象,我试过
function ab(n){this.name=n;};
var c= new ab("abcde");
console.log(c);
Object.defineProperty(c, 'name', {
get: function() {
return name;
},
set: function(Name) {
this.name = Name;
}
});
c.name="xyz";
console.log(c.name);
Run Code Online (Sandbox Code Playgroud)
这里我首先使用构造函数创建对象,然后使用get和set.但我收到错误"超出最大调用堆栈大小".我没有得到这个错误的原因.感谢帮助
Tho*_*mas 25
我认为已经解释过,this.name = Name在setter中再次调用setter,导致无限递归.
这个方法怎么样:
function Ab(_name){
Object.defineProperty(this, "name", {
//enumerable: true, //maybe?
get: function(){ return _name },
set: function(value){ _name = value }
});
}
var c = new Ab("abcde");
console.log(c, c.name);
Run Code Online (Sandbox Code Playgroud)
或者原型方法的
缺点:私有财产_name是公共的
function Ab(n){
this.name = n;
}
Object.defineProperty(Ab.prototype, "name", {
get: function(){ return this._name },
set: function(value){ this._name = value }
});
Run Code Online (Sandbox Code Playgroud)
或ES6
与原型aproach 几乎相同
class Ab{
constructor(n){
this.name = n;
}
get name(){ return this._name },
set name(value){ this._name = value }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13625 次 |
| 最近记录: |