我想創建一系列從基礎對象繼承或複製實例屬性的對象。這導致我決定使用哪種模式,並且我想問你的意見,哪種方法「更好」。克隆還是應用:哪個更好?
//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