When it comes to using a JavaScript constructor to return a JavaScript object literal or simply setting properties with this.XYZ
, are there any performance or functional differences? Consider the following example:
function PersonA(fname, lname) {
this.fname = fname;
this.lname = lname;
}
function PersonB(fname, lname) {
return {
"fname": fname,
"lname": lname
};
}
Both options appear 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 approach preferable for any specific reason, or is it purely a matter of personal preference? If just a matter of preference, is one considered more standard than the other?