getter setter超出最大调用堆栈大小错误

Rol*_*wal 16 javascript

我正在尝试学习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)


ris*_*dev 7

set 语法将对象属性绑定到要在尝试设置该属性时调用的函数。

您不需要执行this.name = Name; 内部设置功能。这会递归地触发设置器,导致堆栈溢出。事实上,在这种情况下,您完全不需要设置器。仅当您在设置或修改属性时必须执行一些额外的工作时才使用 setter。

更多的