gpt4 book ai didi

javascript - 返回一个在对象文字上定义的 setter/getter ?

转载 作者:行者123 更新时间:2023-11-30 20:58:23 24 4
gpt4 key购买 nike

请看一下函数 Y 如何“重用”函数 X 的 itemCount getter。我认为我应该能够将其定义为 itemCount: x.ItemCount,但这不起作用。

问题:有人可以解释为什么我必须执行以下操作才能从 Y 返回 X 的 itemCount 吗?必须有一些东西可以使普通功能变得特别。

// Returns simple object literal with 2 properties.
function X () {
return {
items: {
1: {},
2: {}
},
get itemCount () {
return Object.keys(this.items).length;
}
}
}

// Returns a simple object literal with the same 2 properties as its "x" arg.
function Y (x) {
return {
items: x.items,
get itemCount () {
return x.itemCount;
}
};
}

var x = new X();
var y = new Y(x);
y.itemCount; // returns 2

最佳答案

如果您使用函数而不是 getter,则必须绑定(bind) this 的值.

例如像这样:

function X () {
return {
items: {
1: {},
2: {}
},
itemCount: function() {
return Object.keys(this.items).length;
}
}
}

function Y (x) {
return {
items: x.items,
itemCount: x.itemCount.bind(x)
};
}

当您调用 x.itemCount()this 的值在 x 的上下文中但是如果你调用y.itemCount() ( y 是从 Y(x) 创建的对象) this将在 y 的上下文中.

为了解决这个问题,您需要绑定(bind) this变量使用 bind() .

关于javascript - 返回一个在对象文字上定义的 setter/getter ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47400731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com