JavaScript:如何制作对象的副本? [英] JavaScript: How to make a copy of a object?

查看:61
本文介绍了JavaScript:如何制作对象的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建对象a的副本,而不必手动将其属性输入对象b.在此代码中,b只是指a.我想创建a的新版本,以便在将属性添加到b时无法通过a看到.

I am trying to create a copy of object a, without having to manually enter its property's into object b. In this code, b simply refers to a. I want to create a new version of a, so that when I add a property to b, it is not visible through a.

var a = new Object(); // create an empty object
var b = a;             // now b refers to the same object
b.test = 1;            // add a new property to b
alert(a.test);         // => 1: the new property is also visible through a
a === b;               // => true: a and b refer to the same object

推荐答案

使用Javascript对象和equals( = )运算符时必须要小心.该运算符不会创建对象的副本,而只会为原始内部对象分配引用.

You have to be careful when working with Javascript objects and the equals (=) operator. This operator does not create a copy of the object, but only assigns a reference to the original internal object.

这意味着在您的情况下, b 不会存储 a 的值,但是会在调用

That means that in your case, b does not store the value(s) of a, but after calling

var b = a;

a b 都指向内存中的同一对象!因此,更改 b 的任何属性也会将它们更改为 a (同样:它们在内部是同一对象).

both a and b point to the same object in memory! Therefore, changing any properties of b also changes them for a (again: they're the same object internally).

要创建对象的副本,您必须手动复制该对象的每个属性:

To create a copy of an object you have to manually copy every property of it:

var a = {};  // create an empty object
a.prop1 = 1; // set a property of this object
var b = {};  // create another empty object
b.prop1 = a.prop1; // copy all properties (in this case: only one) of a to b
b.test = 1;  // add a new property to b
alert(a.test); // => undefined, as .test is only defined for b
a === b; // => false, as a and b are different objects.

可以在以下位置找到解决克隆JS对象问题的优雅解决方案:

An elegant solution to the problem of cloning JS-objects can be found here: How do I correctly clone a JavaScript object?

这篇关于JavaScript:如何制作对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆