Someone can explain me in the following code, why when I do o = {}, the object is not being reset?
var funky = function (o) {
o.z = null;
o.a = "aaa";
o = {};
};
var x = { z: "zzz"};
funky(x);
console.log(x);
Someone can explain me in the following code, why when I do o = {}, the object is not being reset?
var funky = function (o) {
o.z = null;
o.a = "aaa";
o = {};
};
var x = { z: "zzz"};
funky(x);
console.log(x);
Because JavaScript doesn't pass by reference. It passes references by value.
The difference is subtle, but important. The gist of it is, the value of an object variable isn't an object; it is a reference to an object. Passing a variable passes a copy of that reference. With it you can modify the content of the object virtually at will, but you couldn't replace it with a whole other object in a way the caller could see.
o
is just an alias to whatever it's currently pointing, it's not the instance (pass by value).
If you want to emulate "pass by reference", you can do it:
var x = { ... };
var container = { x: x };
funky(container);
Now you can reset it in funky()
:
container.x = {};