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

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

问题描述

有人可以帮助我理解 '_' 字符在 javascript 的 setter 和 getter 中的重要性.例如,我有以下代码可以正常工作.

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 该属性.当这种情况发生时,getter 被触发.使用您的第二个示例,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 的属性不同.由 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.

同样的想法也适用于 setter.

The same idea applies to the setter.

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

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