I want to create a series of objects that inherit or copy instance properties from a base object. This has led me to a decision about which pattern to use, and I wanted to ask your opinions about which method was "better".
//APPLY:
// ---------------------------------------------------------
//base object template
var base = function(){
this.x = { foo: 'bar'};
this.do = function(){return this.x;}
}
//instance constructor
var instConstructor = function (a,b,c){
base.apply(this);//coerces context on base
this.aa = a;
this.bb = b;
this.cc = c;
}
instConstructor.prototype = new base();
var inst = function(a,b,c){
return new instConstructor(a,b,c);
}
//CLONE
// ---------------------------------------------------------
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var x = {foo: 'bar'};
function instC(a,b,c){
this.aa = a;
this.bb = b;
this.cc = c;
this.x = clone(x);
};
instC.prototype.do = function(){
return this.x;
}
they both achieve the same thing, namely unique instance properties based on a common template - the question is which one is more "elegant"