getter setter超出最大调用堆栈大小错误 [英] getter setter Maximum call stack size exceeded Error

查看:129
本文介绍了getter setter超出最大调用堆栈大小错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习get和设置JavaScript对象,我试过了

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

这里我首先使用构造函数创建对象,然后使用get和set。但我收到错误超出最大调用堆栈大小。我没有得到这个错误的原因。感谢您的帮助

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

推荐答案

我认为已经解释过, this.name = Name 在setter中再次调用setter,导致无限递归。

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

这个方法怎么样:

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

或原型方法

下行:私有财产 _name 是公开的

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

或ES6

与原型aproach几乎相同

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 }
}

这篇关于getter setter超出最大调用堆栈大小错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆