0

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();

dumbass
27.2k4 gold badges43 silver badges77 bronze badges
asked Mar 24, 2015 at 15:16
1
  • 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. Commented Dec 27, 2024 at 15:44

2 Answers 2

0

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.

answered Mar 24, 2015 at 15:20
Sign up to request clarification or add additional context in comments.

Comments

-1

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

answered Mar 24, 2015 at 15:20

7 Comments

Thanks for the efforts in changing the above code. But I am actually looking for an answer that will help me understand the behavior of the closure function code mentioned by me so that I can know why the error.
the b1 value is overwritten by the b2 when you call the new B(".."), this is causing your issue.
does b1 and b2 do not have separate references?
maybe this sample may help you understand what is going on with the 'name' variable: jsfiddle.net/7e54ywxd/1
they are separated but the name variable is shared, so it can be overwritten. You can either include it inside the function as per Andy's sample or modify the code as suggested by me
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.