7

Consider the following code:

var ob = {}
var ref1 = ob;
var ref2 = ob;
var ob2 = { ref3: ob };

Now I want to get a list of all 4 references to the object by one of them (ob, ref1, ref2, ob2.ref3)

Is it possible? Is there a way to get info how much references the object has if not?

UPDATE

Explanation

I need to register a class instance instead of previous one in a third party class hierarchy and I need to know where old one was referenced from

humkins
  • 9,635
  • 11
  • 57
  • 75
  • No, it's not possible. Why you even need them? All this refs are exactly same. – vp_arth Jul 19 '16 at 10:22
  • No, values do not know anything about the variable/property that holds them – Patrick Evans Jul 19 '16 at 10:23
  • You want to get those "references" how? This is rather meaningless. You cannot put "variables" into variables. You could hypothetically get the *variable names* as strings, but that's also rather meaningless, since those names mean different things in different scopes. – deceze Jul 19 '16 at 10:23
  • You should trust in garbage collector here. It **knows** :) – vp_arth Jul 19 '16 at 10:25

2 Answers2

7

No, you cannot do that.

There's no feature in JavaScript to enumerate other copies of the reference to an object1, nor a feature telling you how many copies of the reference exist. So in the absense of that feature, to do it, you'd have to first find all global and local variables, constants, object properties, etc. that might refer to the object, and compare them with the reference you have to see if they match. That's impossible, you cannot access all globals (as of ES2015), nor all local variables (for instance, referenced by closures); if it were possible, it would pobably be impractical.

1 Not least because JavaScript has no concept of references to individual variables at a code level, so there's no way for the enumeration to provide you with the information, since it can't point you at the variable.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

No, all of the assignments will be still the same object / address reference.

Oskar Szura
  • 2,469
  • 5
  • 32
  • 42