Raviteja Avvari
Raviteja Avvari

Reputation: 250

Function behavior confusion

I am confused why this below code outputs only the b2 value. What happens to b1?

var B = (function(){
  var name = "";
  return function(n){
    name = n;
    this.sayHello = function(){
      console.log("Hi " + name);
    }
  }
})();

var b1 = new B("xxx");
var b2 = new B("yyy");

b1.sayHello();
b2.sayHello();

Upvotes: 0

Views: 30

Answers (2)

Andy
Andy

Reputation: 63524

If you declare name within the closure it will work. My guess is that if you don't declare that variable within its scope the closure will always use the outer declared version of name which in your example will always be yyy because that's the last value it is set to.

var B = (function () {
    return function (n) {
        var name = n || 'David';
        this.sayHello = function () {
            alert("Hi " + name);
        }
    }

})()

DEMO

Note, to prevent and error being created if nothing is passed into the constructor, I've added a default option, 'David' in this case.

Upvotes: 0

Sim1
Sim1

Reputation: 532

the correct code to test is the following:

var B = (function(){
    var name = "";
  return function(n){
     name = n;
    this.sayHello = function(){
          alert("Hi " + name);
     }
  }

})()

var b1 = new B("xxx");
b1.sayHello();

var b2 = new B("yyy");
b2.sayHello();

if you call var b1 = new B("xxx"); and then var b2 = new B("yyy"); the variable name is overwritten, leading to the weird behavior you've noticed.

Demo

Upvotes: -1

Related Questions