首页 > 解决方案 > javascript 对象内的模板文字 [es6]

问题描述

我如何将对象值分配给对象的其他键。我试过了,但它不起作用我得到的只是未定义。

let test = {
 id:1,
 name:this.test.id
}

let test2 = {
 id:1,
 name:`hello, ${this.id}`
}

console.log(test)
console.log(test2);

标签: javascripttypescriptecmascript-6

解决方案


创建对象时,是创建对象this的上下文,而不是对象本身(因为它还不存在)。使用 getter 来计算值。

let test = {
 id:1,
 get name() { return this.id }
}

let test2 = {
 id:1,
 get name() { return `hello, ${this.id}` }
}

console.log(test)
console.log(test2);


推荐阅读