Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all object references in Javascript [duplicate]

Tags:

javascript

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

like image 675
humkins Avatar asked Jul 19 '16 10:07

humkins


People also ask

Does JavaScript copy object by reference?

Passing variables to functions is working the same way like copying for the same data types in most of the languages. In JavaScript primitive types are copied and passed by value and objects are copied and passed by reference value.

What is JavaScript clone ()?

Cloning in javascript is nothing but copying an object properties to another object so as to avoid creation of an object that already exists. There are a few ways to clone a javascript object. 1) Iterating through each property and copy them to a new object. 2) Using JSON method.

How do you avoid reference copy in TypeScript?

So everyone needs to copy an object into another variable but we don't need to reference it, we need to create a new object from the copying object. So, on JavaScript & TypeScript languages, we have the option to do that in multiple ways. But we have used the “newObject = {… Object}” thing commonly in typescript.

How do you copy properties from one object to another object in JavaScript?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


1 Answers

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.

1Not 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.

like image 122
T.J. Crowder Avatar answered Sep 16 '22 11:09

T.J. Crowder