Javascript getter和setters-递归问题 [英] Javascript getters and setters - recursion issue

查看:94
本文介绍了Javascript getter和setters-递归问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我理解javascript设置程序和获取程序中'_'字符的重要性.例如,我有下面的代码可以正常工作.

Can someone please help me understand the significance of the '_' character in the setters and getters of javascript. For example I have the following code which works fine.

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

var me = user;
me.name = "Rob";

alert(me.name);

但是,如果我删除了下划线,那么我的代码将如下所示,那么我的代码将无法工作,并且在浏览器控制台中将显示一个错误,指出"RangeError:超出了最大调用堆栈大小."

But if I remove the underscore so my code will look like the following, then my code won't work and I get a an error in the browser console stating "RangeError: Maximum call stack size exceeded."

var user = {
    get name() {
        return this.name;
    },    
    set name(value) {
        this.name = value;
    }
};

var me = user;
me.name = "Rob";

alert(me.name);

</script>

有人可以告诉我在这种情况下"_"的作用吗?

Can someone please explain to me what the "_" does in this situation?

推荐答案

这很简单.在第二个示例中,get会自行调用.

It's quite simple. In your second example, the get, calls itself.

由于您引用了属性me.name,因此JavaScript需要将该属性get设置为get.发生这种情况时,将触发吸气剂.在第二个示例中,JavaScript调用了getter,但是然后告诉getter做完全相同的事情:获取要处理的属性.该函数总是调用自身,使其无限递归.

Since you reference the property me.name, JavaScript needs to get that property. When this happens, the getter is triggered. Using your second example, JavaScript calls the getter, but the getter is then told to do the exact same thing: get the property that it is meant to handle. The function always calls itself, making it infinitely recursive.

但是,在第一个示例中,在getter中检索的属性与最初触发getter的属性不同.为了避免上述递归问题,由吸气剂获取的值在某种程度上是一个存储组件.尽管这两个属性的名称相似,但它们之间并没有实际的联系.

However, in the first example, the property that is being retrieved in the getter is not the same as the one that originally triggered the getter. The value being retreived by the getter is somewhat of a storage component to avoid the problem of recursion mentioned above. The two properties have no actual connection between them even though they have similar names.

同样的想法也适用于二传手.

The same idea applies to the setter.

这篇关于Javascript getter和setters-递归问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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