是否可以通过某种方式动态地组成字符串?我已经读过一些关于值传递和引用传递的信息,因此我将所有字符串创建为对象。
示例:
var foo = {str: 'foo'};
var bar = {str: foo.str + 'bar'};
var baz = {str: bar.str + 'baz'};
foo.str = 'fuu';
console.log(baz.str); //expected 'fuubarbaz', got 'foobarbaz
谢谢!
答案 0 :(得分:3)
不,当您像这样静态定义事物时,他们将在调用该变量时使用该变量。您可以使用getters来做类似的事情:
let foo = {str: 'foo'};
let bar = {get str() { return foo.str + 'bar'; }};
let baz = {get str() { return bar.str + 'baz'; }};
foo.str = 'fuu';
console.log(baz.str); // properly outputs `fuubarbaz`
之所以有效,是吸气剂的魔力;而不是静态定义属性,而是定义一个在尝试访问属性时调用的函数。通过这种方式,它可以“响应”任何下游更改,因为它始终是动态生成的。
答案 1 :(得分:1)
它不能像这样工作,串联foo.str +
仅执行一次,加号不是被多次调用的函数。
一种执行所需操作的方法是创建一个具有3个字符串和一个方法的对象!:
const obj = {
a: 'foo',
b: 'bar',
c: 'baz',
show: function() {
return this.a + this.b + this.c;
}
};
console.log(obj.show());
obj.a = 'fuu';
console.log(obj.show());
答案 2 :(得分:0)
基于puddi的回答,我想到了这一点:
console.clear()
var foo = {
// _str is the storage of str
_str: 'foo',
// getter of str, always called when accessing str in a read context
get str() {return this._str},
// setter of str, always called when accessing str in a write context
set str(str) {this._str = str}
};
// read context, so get str() of foo is called
console.log(foo.str) // "foo"
var bar = {
// define getter function of bar, calls getter function of foo
get str() {return foo.str + 'bar'}
};
// read context, so get str() of bar is called
console.log(bar.str) // "foobar"
var baz = {
// define getter function of baz, calls getter function of baz
get str() {return bar.str + 'baz'}
};
// read context, so get str() of baz is called
console.log(baz.str) // "foobarbaz"
// write context, so set str(str) of foo is called. foo._str is now 'fuu', was 'foo'
foo.str = 'fuu';
// read context, getter of baz is called which calls getter of bar which calls getter of foo which returns _str which has the value of 'fuu'
console.log(baz.str); // "fuubarbaz"
或者,您可以使用Object.defineProperty:
console.clear();
var foo = Object.defineProperty({}, 'str', {
enumerable: true,
get: () => this._property_str,
set: (str) => this._property_str = str
});
var bar = Object.defineProperty({}, 'str', {
enumerable: true,
get: () => foo.str + 'bar',
});
var baz = Object.defineProperty({}, 'str', {
enumerable: true,
get: () => bar.str + 'baz',
});
foo.str = 'foo'
console.log(foo.str) // "foo"
console.log(bar.str) // "foobar"
console.log(baz.str) // "foobarbaz"
foo.str = 'fuu';
console.log(baz.str); // "fuubarbaz"