Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

javascript - getter setter Maximum call stack size exceeded Error

I am trying to learn get and set in JavaScript object for that I tried

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); 

Here I am first making object using constructor and then using get and set. But i am getting error "Maximum call stack size exceeded". I am not getting the reason of This Error . Thanks for help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think it has already been explained, that this.name = Name in the setter calls again the setter, wich leads to an infinite recursion.

How about this aproach:

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);

Or the prototypal-approach
downside: the private property _name is a public

function Ab(n){
    this.name = n;
}
Object.defineProperty(Ab.prototype, "name", {
    get: function(){ return this._name },
    set: function(value){ this._name = value }
});

Or ES6
pretty much the same thing as the prototypal aproach

class Ab{
    constructor(n){
        this.name = n;
    }

    get name(){ return this._name },
    set name(value){ this._name = value }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...