javascript - javascript 对象内的模板文字 [es6]
问题描述
我如何将对象值分配给对象的其他键。我试过了,但它不起作用我得到的只是未定义。
let test = {
id:1,
name:this.test.id
}
let test2 = {
id:1,
name:`hello, ${this.id}`
}
console.log(test)
console.log(test2);
解决方案
创建对象时,是创建对象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);
推荐阅读
- node.js - 如何在 node.js 中实现多项选择
- excel - VSTO vb.NET - 获取现有工作表控件的名称
- php - 数据库数据以单行显示
- python - 如何有条件地对 Pandas 数据框求和
- android - 我正在使用 FirebaseUi 多重登录方法,但如何授予每个人登录应用程序的权限..?
- node.js - 在angular8应用程序中成功登录后打印用户名
- c# - Ubuntu MATE ARM32 上的 Azure 语音 SDK 意图识别错误
- javascript - 作为参数的函数:练习
- resharper - 我可以在本地函数中专门为参数设置命名样式吗?
- android - ImageView 在 Android 中脱离布局