简体   繁体   中英

Javascript Variable Assignment of Object While Maintaing Reference

I have two variables referring to the same object so that objectA === objectB is true. I want to be able to assign {} to objectB and have objectA hold {} as well however whenever I do this I'm really just changing objectB's reference to wherever {} is (I think) so now objectA and objectB refer to different things. I have a way to do it, objectA = objectB = {}, but I don't like this because it requires a circular reference in my implementation. Is this possible or is there a better way?

创建一个复制构造函数以将一个对象的值复制到另一个对象,然后objectA和objectB将不相等,但它们在属性中具有相同的值。

Is this what you want to achieve?

a = { foo:'Bar' }

b = Object.create(a) Create a new object that has the object a as prototype.

a == b is false

b.foo is "bar"


Setting a property in a will make it available in b too through the prototype chain.

a.foo = "qux"

b.foo is "qux" too.


It doesn't work the other way around:

b.other = 'a'

a.other is undefined .


Note that Object.create is part of ECMA Script 5, and need to check if your target browsers support it: http://kangax.github.io/es5-compat-table/#Object.create

In order to do that without extra clutter, you'd need a variable that can refer to another variable. That isn't possible in JavaScript -- variables and properties refer only to values , and are passed around strictly by value. That means that the reference in A is a copy of the one in B, and assigning a new reference to one can not affect the other directly.

You could achieve a similar effect, though, by having A and B point at the same (possibly empty) object, and then modifying a property of that object. Since both variables refer to the same object, the property change will appear in both places. It's a little clumsier than built-in C++-style reference variables, but it works if both sides know the rules.

(The big difference is, this setup won't let you arbitrarily set variables that weren't shared this way. But frankly, i'd consider that a good thing.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM