3

我想创建一系列从基础对象继承或复制实例属性的对象。这使我决定使用哪种模式,我想询问您对哪种方法“更好”的意见。

//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;
}

它们都实现了相同的目标,即基于通用模板的唯一实例属性 - 问题是哪个更“优雅”

4

2 回答 2

2

根据您的问题,您似乎正在寻找类似于Object.create的东西。此函数可用于创建一个新对象,该对象具有您选择的对象作为原型。

//for old browsers without Object.create:
var objCreate = function(proto){
    function F(){};
    F.prototype = proto;
    return new F();

至于与克隆方法的比较,它们会做不同的事情,因此您必须选择更合适的方法。

使用原型将反映对子对象的父对象的更改。

a = {x:1};
b = Object.create(a);
a.x = 2;
//b.x is now 2 as well

您还必须小心使用具有this. 如果您使用过多的原型继承,可能会产生不良后果,具体取决于您所做的事情。

a ={
   x: 1,
   foo: function(){ this.x += 1 }
}
b = Object.create(a);
b.foo();
//a.x does not change

另一方面,克隆会克隆东西,因此您可以确保对象不会以任何方式相互干扰。有时这就是你想要的。

于 2011-11-10T11:02:51.480 回答
0

好的,所以我对此进行了进一步的思考——答案源于用例。clone 将属性复制到给定范围内,apply 正在更改属性周围的范围。前者更适合mixins,后者更适合继承。

于 2011-11-14T20:44:43.730 回答