简体   繁体   中英

Alias for attribute object in JavaScript

I would like to know if in Js exists something to "redefines var or object" like in other Languages. Something like an "alias"

For Example I have an object

var obj1 = new Object();

This has an attribute attr1 and object2.

obj1.attr1 = 'a';
obj1.obj2 =  new Object();

Is it possible that I have 'alias_attr1' and 'alias_obj1' and both they are same that attr1 and obj2 ?

Thanks

If I recall correctly, objects are passed by reference, but they reference the same object if you don't clone it. Primitives aren't. So if you have the following:

var obj1 = {
    "id" : 7
};
var obj2 = {
    "one" : "a",
    "two" : "a",
    "three" : obj1,
    "four" : obj1
};
console.log(obj2.three === obj2.four) // -- > true

Since obj1 is an object and you don't clone it, both obj2.three and obj2.four reference the same object. obj2.one and object2.two however, are strings, and they don't reference eachother, even though they have the same value.

But it doesn't stop there, you can overwrite the objs seperately. So if you set obj1 to something else, obj2.three and obj2.four will still contain the original obj1. obj1 = 'test'; --> obj2 stays the same.

However, if you update obj1 instead of overwriting it, either directly obj1.id = 8; or indirectly obj2.three.id = 8; , the changes will be seen in obj2.four: (obj2.four.id === 8) // --> true

So it's a bit complicated and I'm not the best to explain this, but there's multiple blogs about it you can find on your fav search engine.

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