JavaScript对象克隆 [英] JavaScript object cloning
本文介绍了JavaScript对象克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能解释为什么 obj
返回 {a:2}
而不是 { a:1}
在这种情况下?
Can anyone explain why the obj
returns {a:2}
instead of {a:1}
in this case?
var obj = {a:1};
var data = {b:obj};
data.b.a = 2;
console.log(obj); // {a:2}
推荐答案
javascript中的对象是通过引用,因此当您更改一个引用时,您也会对其进行更改。意思是您刚刚创建了一个浅表副本,您需要做一个深层克隆。
objects in javascript are by reference, so when you change one reference you changed them. The meaning of this is you just created a shallow copy, you need to do a deep clone.
深层副本可以用jQuery这样制作:
Deep copy can be made with jQuery this way:
// Deep copy
var newObject = jQuery.extend(true, {}, obj);
请阅读以下使用jQuery的原因:
在JavaScript中深度克隆对象的最有效方法是什么?
(这是Stackoverflow上的John Resig)。 ..)
Read this why I used jQuery:
What is the most efficient way to deep clone an object in JavaScript?
(It's John Resig here on Stackoverflow...)
这篇关于JavaScript对象克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文