克隆或应用:哪个“更好”

clone or apply : which is "better"?

本文关键字:更好 哪个 应用      更新时间:2023-09-26

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

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

它们都实现了同样的事情,即基于共同模板的唯一实例属性——问题是哪一个更"优雅"

听你的问题,看起来你正在寻找类似于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
另一方面,克隆克隆内容,因此您可以确保对象不会以任何方式相互干扰。有时候这正是你想要的。

好的,所以我对这个问题进行了进一步的思考——答案来自用例。其中clone是将属性复制到给定的作用域,apply是更改围绕该属性的作用域。前者更适合混合,后者更适合继承。