简体   繁体   English

如何更新使用javascript中的模板文字的对象值?

[英]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的对象值?

In file1 在文件1中

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

In file2 在文件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
}

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.

相关问题 我如何使用 intellij 在 javascript 中更漂亮的模板文字 - how can i prettier template literal in javascript with intellij 如何创建使用文字字符串(Javascript)的多级数组? - How to create multi level array which uses literal strings (Javascript)? 如何将JavaScript对象文字的字符串转换为JavaScript对象文字? - How can I convert the string of a JavaScript object literal to a JavaScript object literal? 如何在JavaScript中检查对象文字的名称? - How Can I Check a Object Literal's Name in JavaScript? 淘汰赛:如何将模型传递给j​​avascript对象文字? - Knockout: how can I pass a model to a javascript object literal? 如何区分 object 文字和其他 Javascript 对象? - How can I differentiate between an object literal other Javascript objects? 如何将JSON字符串转换为JavaScript Object Literal - How can I convert my JSON string to a JavaScript Object Literal 无法更新Javascript对象文字中的值,然后更新页面 - unable to update value within a Javascript object literal, and then update the page 如何将键/值对添加到嵌套对象文字中? - How can I add a key/value pair to a nested object literal? 如何在对象文字分配中指定动态值? - How can I specify dynamic value in object literal assignment?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM