我正在用javascript创建对象。但是,我知道我正在使用新的className()运算符。我想知道是否可以创建副本构造函数,以便在创建新对象(即var object1 = object2)时,仅将object2中的成员变量复制到object1中,而不将其复制到指针中。谢谢!
JS不会自动为任何对象生成构造函数-复制,移动或其他方式。您必须自己定义它们。
最接近的是类似的东西Object.create
,它需要一个原型和一个现有的对象来复制属性。
要定义副本构造函数,可以从以下几行开始:
function Foo(other) {
if (other instanceof Foo) {
this.bar = other.bar;
} else {
this.bar = other;
}
}
var a = new Foo(3);
var b = new Foo(a);
document.getElementById('bar').textContent = b.bar;
<pre id="bar"></pre>
使用它来支持深度复制只是相同模式的递归:
function Foo(other) {
if (other instanceof Foo) {
this.bar = new Bar(other.bar);
} else {
this.bar = new Bar(other);
}
}
function Bar(other) {
if (other instanceof Bar) {
this.val = other.val;
} else {
this.val = other;
}
}
Bar.prototype.increment = function () {
this.val++;
}
Bar.prototype.fetch = function () {
return this.val;
}
var a = new Foo(3);
var b = new Foo(a);
a.bar.increment();
document.getElementById('a').textContent = a.bar.fetch();
document.getElementById('b').textContent = b.bar.fetch();
<pre id="a"></pre>
<pre id="b"></pre>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句