-4

Please give me some link to help me understand this

    var obj = {
  a: 1
};
(function(obj) {
  obj = {
    a: 2
  };
})(obj);
console.log(obj.a);

logs out 1 whereas this

var obj = {
  a: 1
};
(function() {
  obj = {
    a: 2
  };
})();
console.log(obj.a);

logs out 2

faizan
  • 172
  • 1
  • 9

1 Answers1

-3

It is because in example 1 you are creating a new name obj as a parameter and it's getting overridden instead of using the passed in value. In example 2, obj is being closed around and replaced.

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445