JavaScript getter/setter 和扩展对象
我正在研究 JavaScript 中的 getter 和 setter,以及它们与扩展对象的扩展函数(如 jQuery 的 $.extend 和 Underscore 的 _.extend)的配合情况。代码设置如下:
var test = {
get size() { return this._size; },
set size(val) { this._size = val; },
}
test.size = "LARGE";
console.log(test.size);
//$.extend(test, { get size() { return "MEDIUM"; } });
_.extend(test, { get size() { return "MEDIUM"; } });
console.log(test.size);
test.size = "SMALL";
console.log(test.size);
在 Chrome 和 Firefox 中我得到:
LARGE
MEDIUM
SMALL
有人能解释一下那里发生了什么吗?为什么调用原来的setter后,原来的getter也恢复了?
I'm researching getters and setters in JavaScript and how well they go with spread functions for extending objects, like jQuery's $.extend and Underscore's _.extend. The code setup is as follows:
var test = {
get size() { return this._size; },
set size(val) { this._size = val; },
}
test.size = "LARGE";
console.log(test.size);
//$.extend(test, { get size() { return "MEDIUM"; } });
_.extend(test, { get size() { return "MEDIUM"; } });
console.log(test.size);
test.size = "SMALL";
console.log(test.size);
In Chrome and Firefox I get:
LARGE
MEDIUM
SMALL
Can someone explain me what's happening there? Why after call the original setter, the original getter is also restored?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Underscore 的
extend
看起来像这样:它迭代源对象的属性,将它们添加到目标对象,然后返回目标对象。当它将
size
属性复制到您要扩展的对象时,它基本上会执行以下操作:也就是说,它使用新对象的 getter,但仅复制该 getter 返回的值。它不转移吸气剂本身。
为了进一步演示这一点,请尝试以下操作:
仅输出:(
它不会迭代 getter 或 setter。)
Underscore's
extend
looks like this:It iterates the source object's properties, adds them to the target object, and then returns the target object. When it copies the
size
property to the object you're extending, it basically does this:That is, it uses the new object's getter, but copies only the value returned by that getter. It doesn't transfer the getter itself.
To further demonstrate this, try the following:
Which outputs only:
(It doesn't iterate the getters or setters.)