我想创建一系列从基础对象继承或复制实例属性的对象。这导致我决定使用哪种模式,并且我想问你的意见,哪种方法“更好”。克隆还是应用:哪个更好?
//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;
}
它们都实现了基于一个通用模板同样的事情,即独特的实例属性 - 问题是更“优雅”
真的可以设置'inst.prototype = ...'_before_你指定'inst'等于下一行的函数吗?这应该是'instConstructor.prototype = ...' – nnnnnn
好点 - 对不起 - 这是一个错字 – sunwukung