【问题标题】:How can I update an object value which uses a template literal in javascript?如何更新在 javascript 中使用模板文字的对象值?
【发布时间】:2018-07-13 16:08:23
【问题描述】:

如您所见,对象 obj2 正在使用 obj1 中定义的模板字面量。 如何在调用 func() 时更新 obj2 中 title 的对象值?

在文件 1 中

let obj1 = { name: 'abc' }, 
obj2 = { title : `${obj1.name}` } 

在文件2中

import {obj1, obj2} from 'file1';

func();

func() {
let obj1 = _.clone(obj1), obj2 = _.clone(obj2);
obj1.name = 'Title of this Page';
console.log(obj2.title) // Still shows abc
}

【问题讨论】:

  • 模板文字不是实时绑定..
  • @Keith - 非常简洁。

标签: javascript string object template-literals


【解决方案1】:

你不能,模板字面量在其内部的对象初始化器被评估时被评估并变成了一个字符串。 obj.title 是正在评估的模板文字的 result(字符串¹),而不是某种模板对象。模板字面量就是这样:一个 literal notation 在遇到它时被评估(就像一个 string literal 被评估,当遇到字符串字面量时产生一个字符串) .

相反,您可以将 title 设为您将 name 传递到的函数:

let obj1 = { name: 'abc' }, 
obj2 = { title : name => `${name}` } 

当然,当你想要标题时,你必须调用它。


¹ 一个字符串在这种情况下,因为模板文字是独立的,不附加到标记函数。

【讨论】:

  • (编辑错误。如果您在上面看到${obj1.name} 而不是${name},请点击刷新。)
猜你喜欢
  • 2017-11-19
  • 2021-06-12
  • 2022-01-10
  • 1970-01-01
  • 2020-09-27
  • 2016-07-14
  • 1970-01-01
  • 2016-03-05
  • 2021-05-05
相关资源
最近更新 更多