类构造函数中同一对象内属性值互访报错问题咨询
问题分析与解决方法
错误原因
这不是类构造函数的限制,纯粹是操作时机不对:
当你在对象字面量{ myKeyOne:1, myKeyTwo: this.myObject.myKeyOne +1 }里访问this.myObject时,这个对象还没被赋值给this.myObject——此时this.myObject还是undefined,自然会抛出“无法读取undefined的属性”的错误。
而this.myKeyThree能正常工作,是因为它的赋值语句在this.myObject = { ... }之后执行,此时this.myObject已经完成初始化,能正常访问内部属性。
解决方法
给你三种可行的修复方式:
- 用临时变量缓存值
把myKeyOne的值先存在变量里,再用变量计算myKeyTwo,避免依赖未初始化的对象:
class MyClass { constructor() { const keyOne = 1; this.myObject = { myKeyOne: keyOne, myKeyTwo: keyOne + 1 }; this.myKeyThree = this.myObject.myKeyOne + 1; } }
- 分步骤初始化对象
先创建包含myKeyOne的基础对象,再追加myKeyTwo:
class MyClass { constructor() { this.myObject = { myKeyOne: 1 }; this.myObject.myKeyTwo = this.myObject.myKeyOne + 1; this.myKeyThree = this.myObject.myKeyOne + 1; } }
- 使用getter动态计算
如果myKeyTwo需要始终和myKeyOne保持关联(比如后续修改myKeyOne时myKeyTwo自动更新),可以用getter:
class MyClass { constructor() { this.myObject = { myKeyOne: 1, get myKeyTwo() { return this.myKeyOne + 1; } }; this.myKeyThree = this.myObject.myKeyOne + 1; } }
这里getter里的this指向的是myObject本身,所以能直接访问myKeyOne。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

