Javascript-如何在不重新分配对象属性的情况下更改它们 [英] Javascript - How change object properties without reassign them
问题描述
下面的代码片段暴露了疑问
The snippet below exposes the doubt
var foo = 'something'
var baz = 'other thing'
var obj = {
prop1 : 'my prop',
prop2 : foo, //referencing external variable
prop3 : baz //referencing external variable
}
// here we get the expected obj to be printed
console.log(obj)
// now I change one of the initial variable
foo = 'changed'
// here we get the sabe print as the first, that is the ~problem~
console.log(obj)
因此,如何在不重新分配 obj.prop2 = foo
So, how to print 'changed' on prop2 without reassign obj.prop2 = foo
推荐答案
执行时
var obj = {
prop1 : 'my prop',
prop2 : foo, //referencing external variable
prop3 : baz //referencing external variable
}
prop2
与变量 foo
(或 prop3
和 baz
).发生的一切是读取 foo
的当前值,并将其存储在 prop2
中(对于 baz
和 prop3
).
there is no ongoing link between prop2
and the variable foo
(or prop3
and baz
). All that happens is that the current value of foo
is read, and stored in prop2
(and the same for baz
and prop3
).
如果您需要 prop2
和 prop3
保持链接到 foo
和 baz
,则可以将它们设置为属性与 getters .这些属性是在读取时触发函数调用的属性(还有设置属性时触发函数调用的 setters ):
If you need prop2
and prop3
to remain linked to foo
and baz
, you could make them properties with getters. These are properties that trigger a function call when they're read (there are also setters which trigger a function call when the property is set):
var obj = {
prop1 : 'my prop',
get prop2() { return foo; },
get prop3() { return baz; }
};
访问 obj.prop2
是隐藏的函数调用.由于该函数在 foo
上关闭,因此它将返回 foo
的当前值.
Accessing obj.prop2
is a hidden function call. Since the function closes over foo
, it returns foo
's current value.
实时示例:
var foo = 'something';
var baz = 'other thing';
var obj = {
prop1 : 'my prop',
get prop2() { return foo; },
get prop3() { return baz; }
};
console.log(obj);
foo = 'changed';
console.log(obj);
这篇关于Javascript-如何在不重新分配对象属性的情况下更改它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!