我想创建一系列从基础对象继承或复制实例属性的对象。这使我决定使用哪种模式,我想询问您对哪种方法“更好”的意见。
//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;
}
它们都实现了相同的目标,即基于通用模板的唯一实例属性 - 问题是哪个更“优雅”