gpt4 book ai didi

javascript - 使用另一个属性计算对象属性值

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:51 24 4
gpt4 key购买 nike

我正在定义一个对象,我想用它的另一个属性来计算它的一个属性。

// first the calculation function
const calculateArea = (height, width) => {
return height * width
}

// then the object itself...
const myObj = {
height: 20,
width: 10,
area: calculateArea(this.height, this.width)
}

我以为我可以使用 this.heightthis.width 来访问我定义的对象内的属性,但我得到了

Cannot read 'height' of undefined

我哪里出了问题,解决办法是什么?

最佳答案

问题是,您尝试使用 this 引用您的对象,但它并不存在。您引用的 this 可能是未定义(如您的情况),这会导致“无法读取未定义的 X 属性”错误。

但是,根据具体情况,this 可能会绑定(bind)到上下文中的另一个对象。在这种情况下,您不会收到此错误,并且与绑定(bind)对象对应的任何值都将作为 this 返回。

尝试从检索到的 this 对象中获取值可能会导致两种情况,这两种情况都不是您想要的。

  • 检索到的 this 有一个 widthheight 属性,以便您的函数将获取这些值并计算结果因此。但这些值不会是您在对象中传递的值。

  • 检索到的 this 没有 widthheight 属性,因此您的函数将变得undefined 作为参数,并会相应地抛出错误。

有很多方法可以解决这个问题。这是我的建议:

这里的主要问题是,在构造对象时,会急切地计算 area 的值。卡住该计算并在创建对象后触发它将计算对象内的正确值。

// 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.widththis.height 计算面积。它还将从结果对象中删除 init() 函数,并以您想要的形式返回该对象。

我们只是暂停了一个步骤的计算,让 this 指向正确的上下文,然后继续。

关于javascript - 使用另一个属性计算对象属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41796351/

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