简体   繁体   中英

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. How can I update the object value for title in obj2 upon calling func()?

In file1

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

In file2

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM