PG_
PG_

Reputation: 139

How to check a variable is a real object or just a reference to an object

Considering:

A = {};
A.test = 123;
B = A;
C = {};
for (key in A) C[key] = A[key]; // a crude clone.

In this example, B is a reference to A, C is a deep-copy of A.

I know I can check them by A === B and A === C

But if I don't have an A, can I distinguish "B" and "C" without knowing "A" ?

Upvotes: 2

Views: 144

Answers (2)

jfriend00
jfriend00

Reputation: 707456

A variable in javascript never IS an object but holds a reference to an object. You can think of javascript as containing a bunch of objects and any assignment of that object to a variable is just putting a reference into the variable. So, there is no difference between the first variable to hold a reference to the object and the last one that you assigned it to.

var x = {a: 1};
var y = x;
y.b = 2;

There is no difference between y and x at this point - they both contain references to the same object.

If you make a crude clone like you did, then it's a completely different object with no further connection to the original. Changes to the clone won't affect the original.

Upvotes: 1

hugomg
hugomg

Reputation: 69944

There is no such thing as a "real object" in Javascript. A is also a reference.

If you examine B === C you will be able to find that they are separate objects but you won't be able to tell which one is the "original".

Upvotes: 8

Related Questions