Are there any performance or functional differences between having a javascript constructor return a JavaScript object literal, versus simply setting properties with this.XYZ. For example:
function PersonA(fname, lname) {
this.fname = fname;
this.lname = lname;
}
function PersonB(fname, lname) {
return {
"fname": fname,
"lname": lname
};
}
Both seem to behave appropriately:
PersonA.prototype.fullName = function() { return this.fname + " " + this.lname; };
PersonB.prototype.fullName = function() { return this.fname + " " + this.lname; };
var pA = new PersonA("Bob", "Smith");
var pB = new PersonB("James", "Smith");
alert(pA.fullName());
alert(pB.fullName());
Is one preferable for any reason, or is it a matter of taste? If taste, is one more standard?
They’re not entirely identical.
If you return the object being created from the constructor…
prototypeof the constructorinstanceofavailable as a means of testing which constructor created itThe reason the
fullName()method seems to work forpBis that you’re using thePersonAconstructor for both.FYI, the proper term is “JavaScript object literal”, not “JSON object literal”.
EDIT: You’ve updated the code in the question to use the
PersonBconstructor. Run it again, and you’ll find an Error in the console.