JavaScript getter/setter 和扩展对象

发布于 2024-10-27 08:28:13 字数 597 浏览 4 评论 0原文

我正在研究 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫林﹌晚霞¤ 2024-11-03 08:28:13

Underscore 的 extend 看起来像这样:

 _.extend = function(obj) {
   each(slice.call(arguments, 1), function(source) {
     for (var prop in source) obj[prop] = source[prop];
   });
   return obj;
 };

它迭代源对象的属性,将它们添加到目标对象,然后返回目标对象。当它将 size 属性复制到您要扩展的对象时,它基本上会执行以下操作:

obj['size'] = source['size']

也就是说,它使用新对象的 getter,但仅复制该 getter 返回的值。它不转移吸气剂本身。

为了进一步演示这一点,请尝试以下操作:

var test = {
    get size() { return this._size; },
    set size(val) { this._size = val; },
}   

for (var p in test) {
    console.log(p)
}

仅输出:(

size

它不会迭代 getter 或 setter。)

Underscore's extend looks like this:

 _.extend = function(obj) {
   each(slice.call(arguments, 1), function(source) {
     for (var prop in source) obj[prop] = source[prop];
   });
   return obj;
 };

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:

obj['size'] = source['size']

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:

var test = {
    get size() { return this._size; },
    set size(val) { this._size = val; },
}   

for (var p in test) {
    console.log(p)
}

Which outputs only:

size

(It doesn't iterate the getters or setters.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文