Just wondering if it's possible to update object reference variables if variable is a string? It works, if I assign the whole object, but doesn't work with the string. I could assign also the whole object, but the issue here is that I don't need an object, but I need a string, since it's a global variable of Angular 2 service.
https://jsfiddle.net/009kqqrt/
obj = { var: 'initial' };
a = [{ test: 'old', new: 'no' }, { test: obj.var, new: 'yes' }];
o = { test: obj.var, new: 'yes' };
obj.var = 'objModified';
alert(o.test); // Changes correctly
obj.var = 'arrModified';
alert(a[1].test);
Here is the jsfiddle.
Expected result would be -
first alert - 'objModified' second alert - 'arrModified'
In my case, I get always 'initial'.
I think what you want to do is pass the object reference
var obj = { var: 'initial' };
var a = [{ test: 'old', new: 'no' }, { test: obj, new: 'yes' }];
var o = { test: obj, new: 'yes' };
obj.var = 'objModified';
alert(o.test.var); // Changes correctly
obj.var = 'arrModified';
alert(o.test.var);
Updated fiddle: https://jsfiddle.net/echonax/009kqqrt/2/
If you pass the string reference like, test: obj.var since strings are immutable, it won't change.
The way you wrote it a and o objects reference the value of the obj.var at the time when they are created.
Any changes to that value after they are created are not going to propagate to a and o.
If you want it to work that way you will need to make the test property reference an object instead of referencing the value directly.
obj = { var: 'initial' };
a = [{ test: 'old', new: 'no' }, { test: obj, new: 'yes' }];
o = { test: obj, new: 'yes' };
obj.var = 'objModified';
alert(o.test.var); // o.test=== obj is true
obj.var = 'arrModified';
alert(a[1].test.var); // a[1].test=== obj is true
When you create the array a and the object o, the properties test are initialized with the value of a simple string variable, so theirs values are stored "as value".
obj = { var: 'initial' };
a = [{ test: 'old', new: 'no' }, { test: obj.var, new: 'yes' }];
o = { test: obj.var, new: 'yes' };
If you initialize that with an object reference, like following example:
var obj = { var: 'initial' };
a = [{ test: 'old', new: 'no' }, { test: obj, new: 'yes' }];
o = { test: obj, new: 'yes' };
obj.var = 'objModified';
console.log(o.test.var);
obj.var = 'arrModified';
console.log(a[1].test.var);
You could see that theirs value will modified when the referenced object is modified, that's because theirs value is stored by reference.
I hope it was clear, bye.