This code:
function CHANGE(d, cb){
d.three = 3;
d = {};
console.log("d was changed into:");
console.log(d);
cb();
}
var d = { one: 1, two: 2 };
CHANGE(d, function(){
console.log("d after the callback is: ");
console.log(d);
});
Since d is rewritten in CHANGE(), really ought to show {} as d. However, the result is bizarre:
d was changed into:
{}
d after the callback is:
{ one: 1, two: 2, three: 3 }
So, d had the property three added to it. And that’s OK. Then it was assigned an empty object {}.
I don’t know what to think.
An extra attribute be added in the callback (three), fine.
Then the object is rewritten. Fine. The printout shows that the object was indeed rewritten.
Then, in the callback, it shows the object with the extra three attribute…?!?
It would be consistent if it were either unchanged, or rewritten. But… half changed…?
In fact, there is no need to use a callback to show this. Even this has the same problem:
function CHANGE( o ){
o.three = 3;
o = {};
}
var d = { one: 1, two: 2 };
CHANGE(d);
console.log("d after the function is: ");
console.log(d);
Here d is again the full object including three.
So, any particular reason why I cannot change the object reference altogether, but can change attributes…?
Merc.
This redefines your variable to a new object, so you lose the old reference. This means that the original isn’t altered after this point.
EDIT:
If you want to clear an existing object of its properties and reassign some others, you could use this:
Output:
http://jsfiddle.net/2DxzT/