ベース オブジェクトからインスタンス プロパティを継承またはコピーする一連のオブジェクトを作成したいと考えています。これにより、どのパターンを使用するかについての決定に至りました。どの方法が「より良い」かについて、ご意見をお聞きしたいと思いました。
//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;
}
どちらも同じことを達成します。つまり、共通のテンプレートに基づく一意のインスタンス プロパティです。問題は、どちらがより「エレガント」かということです。