[英]How can I update an object value which uses a template literal in javascript?
As you can see, the object obj2 is using a template literal defined in obj1. 如您所见,对象obj2使用的是obj1中定义的模板文字。 How can I update the object value for title in obj2 upon calling func()?
调用func()后,如何更新obj2中title的对象值?
let obj1 = { name: 'abc' },
obj2 = { title : `${obj1.name}` }
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
}
You can't, the template literal was evaluated and turned into a string when the object initializer it was inside was evaluated. 您不能,对模板文字进行了评估,并在评估其内部的对象初始化程序时将其转换为字符串。
obj.title
is the result of the template literal being evaluated (a string¹), not some kind of template object. obj.title
是字面被评估(一string¹)的模板的结果 ,而不是某种模板对象的。 Template literals are exactly that: A literal notation which is evaluated when it's encountered (just like a string literal is evaluated, resulting in a string, when the string literal is encountered). 模板文字正好是这样:一种文字符号 ,在遇到文字文字时会进行评估(就像评估字符串文字一样,当遇到字符串文字时会生成一个字符串)。
Instead, you might make title
a function you pass name
into: 相反,您可以将
title
作为传递name
的函数:
let obj1 = { name: 'abc' },
obj2 = { title : name => `${name}` }
You have to call it, of course, when you want the title. 当然,在需要标题时必须调用它。
¹ A string in this case , because the template literal was freestanding, not attached to a tag function. ¹ 在这种情况下为字符串,因为模板文字是独立的,未附加到标记函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.