gpt4 book ai didi

javascript - 克隆或应用 : which is "better"?

转载 作者:行者123 更新时间:2023-11-29 15:02:21 28 4
gpt4 key购买 nike

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

//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 的东西。 .此函数可用于创建一个新对象,该对象具有您选择的对象作为原型(prototype)。

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

至于和clone方法的比较,他们做的事情不同,所以你要选择更合适的。

使用原型(prototype)会将父对象的变化反射(reflect)到子对象上。

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

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

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

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

关于javascript - 克隆或应用 : which is "better"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8078265/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com