PDA

View Full Version : Named or unnamed constructor, What's the difference?



hvip
11-18-2013, 04:40 PM
Below are 2 constructor objects, the only difference is the naming. What are the implications of using one or the other?


var PersonT1 = function(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
this.getGender = function(){
return this.gender;
};
};

var PersonT2 = function PersonT2(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
this.getGender = function(){
return this.gender;
};
};

var user1 = new PersonT1("Maria",30,"female");
var user2 = new PersonT2("Ben",40,"male");

console.log(user1);
console.log(user2);

console.log(user1.constructor.name);
console.log(user2.constructor.name);

console.log(user1.getGender());
console.log(user2.getGender());

jscheuer1
11-18-2013, 05:43 PM
Virtually none in this case except that some browsers might not like the second named constructor the way it's written there. In fact they're both "named" (via being assigned to a variable name). The first one is PersonT1, the second is named PersonT2. The PersonT2 syntax is redundant though. It could be simply:


function PersonT2(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
this.getGender = function(){
return this.gender;
};
}

And that's the usual syntax for declaring a constructor function.

A truly unnamed constructor would look like so:


var userX = new (function(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
this.getGender = function(){
return this.gender;
};
})("Sally", 35, "female");
console.log(userX.getGender()); // gives: female