-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,471
  • 17
  • 87
  • 173
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430