In one task I have to change a object by deliver it to a function. it is almost like this:
function change(obj) {
return {
fn1: function() {
obj['three'] = 3;
},
fn2: function() {
obj = {'four':4};
}
};
}
var obj = {'one':1,'two':2};
console.log(obj); // output 'Object {one=1, two=2}'
var temp = change(obj);
temp.fn1();
console.log(obj); // output 'Object { one=1, two=2, three=3}'
temp.fn2();
console.log(obj); // output 'Object { one=1, two=2, three=3}'
fn1 is for changing one of the object's value. As you can see, it intends to set obj[three] to 3 and it works well.
fn2 is for replacing the object of another one. The obj should only contain 'four':4 after the execution。 however it didn't work.
Then I check the value of the obj inside fn2:
...
fn2: function() {
console.log('before fn2',obj);
obj = {'four':4};
console.log('after fn2', obj);
}
};
...
The output is:
'before fn2 Object{one=1,two=2,three=3}'
'after fn2 Object{four=4}'
So it did work inside the fn2. I get confused that fn2 fails while fn1 works. How to fix it?