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)
So, how to print 'changed' on prop2 without reassign obj.prop2 = foo
When you do
var obj = {
prop1 : 'my prop',
prop2 : foo, //referencing external variable
prop3 : baz //referencing external variable
}
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
).
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; }
};
Accessing obj.prop2
is a hidden function call. Since the function closes over foo
, it returns foo
's current value.
Live Example:
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);
Since JavaScript is pass by value instead of pass by reference you cannot override the previous value by assigning it directly to the variable.
You can though make an object of it, and change a property of the object like this:
var foo = {value: 'something'}
var baz = 'other thing'
var obj = {
prop1 : 'my prop',
prop2 : foo, //referencing external variable
prop3 : baz //referencing external variable
}
console.log(obj)
foo.value = 'changed'
console.log(obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With