使用Javascript中的赋值运算符将一个对象设置为等于另一个对象 [英] Setting one object equal to another object with the assignment operator in Javascript

查看:189
本文介绍了使用Javascript中的赋值运算符将一个对象设置为等于另一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C背景的javascript。在javascript中,当我使用赋值运算符将一个对象分配给另一个对象时,它是将值从一个复制到另一个,还是现在它们都指向相同的数据?或者,赋值算子在这种情况下做了什么?

I'm coming to javascript from C background. In javascript, when I use the assignment operator to assign one object to another, does it copy the values from one to the another, or do they both now point to the same data?. Or does the assignment operator do anything in this case?

function point_type()
 {
 this.x = 0;
 this.y = 0;
 }

var pnt1 = new point_type();
var pnt2 = new point_type();

pnt1.x = 4;
pnt1.y = 5;

pnt2 = pnt1;

pnt1.x = 8;
pnt2.y = 9;

在上面的示例中,pnt2.x现在是否等于8,还是等于4,或者它是否仍然等于0?

In the example above, does pnt2.x now equal 8, or does it still equal 4, or does it still equal 0?

是的,我知道我可以自己测试一下,我会在等待社区提出答案时这样做。但是,我希望我的问题的答案只会回过头来回答这个例子,并且可能会对javascript对象的工作原理以及一些最佳实践有所启发。

Yes, I realize I can test this myself, and I will be doing that while I wait for the community to come up with an answer. However, I'm hoping the answer to my question will go one step past just answering this one example and might shine some light on how javascript objects work and some best practices.

跟进问题:

答案似乎是复制了引用。 pnt2和pnt1现在指向相同的数据。是否可以设置我的对象以便复制值?这通常是如何在javascript中完成的?显然,我不希望每次需要复制此对象时都单独设置每个属性。

Follow up question:
The answer seems to be that the reference is copied. pnt2 and pnt1 now point to the same data. Is it possible to set up my object so that the values are copied? How is this usually accomplished in javascript? Clearly I don't want to set each attribute individually every time I need to copy this object.

推荐答案

在JavaScript中,原始类型按值复制,引用类型通过引用复制。更多信息: http://docstore.mik.ua/orelly/web/jscript /ch09_03.html

In JavaScript, primitive types are copied by value and reference types are copied by reference. More info here: http://docstore.mik.ua/orelly/web/jscript/ch09_03.html

这篇关于使用Javascript中的赋值运算符将一个对象设置为等于另一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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