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

查看:46
本文介绍了使用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天全站免登陆