【问题标题】:Calculate object property value with another property用另一个属性计算对象属性值
【发布时间】:2017-06-07 08:56:38
【问题描述】:

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

// 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 来访问我正在定义的对象中的属性,但我明白了

无法读取未定义的“高度”

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

【问题讨论】:

  • 需要在对象创建后调用,在对象定义的时候不能引用对象的属性。
  • const myObj = { height: 20, width: 10, area: function(){ return this.height * this.width } }
  • 当赋值操作采用外部上下文时。

标签: javascript function object this calculation


【解决方案1】:

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

不过,this 可能会根据具体情况绑定到上下文中的另一个对象。在这种情况下,您不会收到此错误,并且与绑定对象对应的任何值都将返回为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 指向正确的上下文,然后继续。

【讨论】:

  • 我只是在寻找这样的解决方案,所以 +1。
【解决方案2】:
function myObj(height, width) {
  this.height = height;
  this.width = width;
  this.area = calculateArea(height, width);
}

let obj = new myObj(20, 10);

【讨论】:

  • 虽然这段代码可能会回答这个问题,但最好在不介绍其他人的情况下解释它是如何解决问题的,以及为什么要使用它。从长远来看,纯代码的答案没有用处。
  • 所提供的答案被标记为低质量帖子以供审核。以下是How do I write a good answer? 的一些指南。这个提供的答案可能是正确的,但它可以从解释中受益。
猜你喜欢
  • 2020-05-17
  • 2021-02-16
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 2022-06-23
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多