For example, I have the following JS object:
var obj = {
n: 0,
o: {}
};
var nGlobal = obj.n;
var oGlobal = obj.o;
And want to use global variables in order to make it look like this:
var obj = {
n: 5,
o: {
x: 7
}
};
Obviously, I am able to assign a value to a property of oGlobal:
oGlobal.x = 7;
However, is there any way to change the value of obj.n through nGlobal, without mentioning obj?
Just something like this:
console.log(obj); // {n: 1, o: {}}
nGlobal.set(5);
// or
nGlobal.value = 5;
console.log(obj); // {n: 5, o: {}}
1 Answer 1
Short answer:
No, there is not.
Long answer:
- In JS primitive types are immutable and passed by values.
- JS implements pass-by-value strategy, which means that ALL data is always passed by value (in case if you pass a reference to object - the reference is passed by value)
One important consequence from the items above: in JS there is no way to change the original object using the = operation. That is: you can modify an object when you have a reference to it, but you cannot swap one object with something else so that all other references also "were modified".
Related:
Credits:
2 Comments
obj.n was an object, nGlobal = someNewObject would magically work (but of course it does not). I guess what's more important here is that primitive values are immutable.Explore related questions
See similar questions with these tags.
with).