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();
-
This question is similar to: What is the scope of variables in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.dumbass– dumbass2024年12月27日 15:44:37 +00:00Commented Dec 27, 2024 at 15:44
2 Answers 2
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);
}
}
})()
Note, to prevent and error being created if nothing is passed into the constructor, I've added a default option, 'David' in this case.
Comments
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.