请看一下函数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,则必须绑定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绑定this变量。
10-08 17:04