【发布时间】: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.height 和 this.width 来访问我正在定义的对象中的属性,但我明白了
无法读取未定义的“高度”
我哪里出错了,解决办法是什么?
【问题讨论】:
-
需要在对象创建后调用,在对象定义的时候不能引用对象的属性。
-
const myObj = { height: 20, width: 10, area: function(){ return this.height * this.width } } -
当赋值操作采用外部上下文时。
标签: javascript function object this calculation