问题是,您试图用 引用您的对象this,而它不存在。您引用的this可能是undefined(如您的情况),然后导致“无法读取未定义的 X 属性”错误。
但是,this根据情况,它可能会绑定到上下文中的另一个对象。在这种情况下,您不会收到此错误,并且与绑定对象对应的任何值都将返回为this.
尝试从检索到的this对象中获取值可能会导致两种情况,这两种情况都不是您想要的。
有很多方法可以解决这个问题。这是我的提议:
这里的主要问题是,area在您构建对象时会急切地计算 for 的值。冻结该计算并在创建对象后触发它将计算对象内的正确值。
// first the calculation function
const calculateArea = (height, width) => {
return height * width
}
// then the object itself...
const myObj = {
height: 20,
width: 10,
// init, is a function that uses bounded context's width, height
init: function() {
this.area = calculateArea(this.height, this.width);
delete this.init; // We don't want init in our result object
return this;
}
}.init();
现在,当我们调用对象的 init() 时,我们将this指向正确的对象。它将用this.width和计算面积this.height。它还将从init()结果对象中删除该函数并以您想要的形式返回该对象。
我们只是暂停计算一步,让我们this的指向正确的上下文,然后继续。