2015-05-08 16 views
0

我正在用javascript創建一個對象。但是,我知道我正在使用新的className()運算符。我想知道如果我可以創建一個拷貝構造函數,所以當我創建一個新對象,即var object1 = object2時,只有object2中的成員變量被複制到object1中,而不是指針。謝謝!Javascript中是否存在複製構造函數?

+0

相關:[最優雅的克隆JavaScript對象的方法](http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object)/ [什麼是最高效的克隆一個對象的方法?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) –

+0

以你描述的方式,沒有。對於其他選項,使用搜索,這個問題有很多重複。 – Nit

+0

如果成員是對象,你想要深度還是淺度拷貝? – webduvet

回答

2

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>