1

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?

depperm
  • 10,606
  • 4
  • 43
  • 67
Black John
  • 31
  • 1
  • 2
  • With the second function, you are changing the assignment of the local variable `obj` from it's original reference and assigning it to a new object. Same base problem as this question: http://stackoverflow.com/questions/30930560/scope-in-javascript-acting-weird/30930727#30930727 – Jesse Kernaghan Jul 02 '15 at 23:27

1 Answers1

2

In JavaScript, arguments are passed by value, though that value often has pointer-like semantics. When you run obj['three'] = 3;, you are not rebinding the variable obj; you are merely changing a property of the object that obj currently holds. On the other hand, when you reassign obj, you are changing the variable obj, not the object that the variable used to hold. You cannot achieve your desired semantics in JavaScript; the best you can do would be to delete all properties of obj and copy over whatever properties you want to be on it.

icktoofay
  • 126,289
  • 21
  • 250
  • 231