Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  3] [ 6]  / answers: 1 / hits: 81514  / 13 Years ago, sun, august 7, 2011, 12:00:00

Is there a reliable way of getting the instance of a JavaScript object?



For example, relying on the fake 'obj.getInstance()' function.



var T = {
Q: {
W: {
C: function() {}
}
}
};

var x = new T.Q.W.C();
console.log( x.getInstance() === T.Q.W.C); // should output true


If this is not part of the ECMA specification, please include browser/node.js support and compatibility in answers.


More From » javascript

 Answers
48

To get a pointer to the instantiating function (which is not a class, but is the type), use obj.constructor where obj is any object.






In JavaScript there are no classes. As such, there are no class instances in JavaScript. There are only objects. Objects inherit from other objects (their so called prototypes). What you are doing in your code is literally defining an object T, which's attribute Q is another object, which's attribute W is another object, which's attribute C is a function.



When you are creating a new instance of T.Q.W.C, you are actually only calling the function T.Q.W.C as a constructor. A function called as a constructor will return a new object on which the constructor function was called (that is with this beeing the new object, like constructorFunction.apply(newObject, arguments);). That returned object will have a hidden property constructor which will point to the function that was invoked as a constrcutor to create the object. Additionally there is a language feature which allows you to test if a given function was used as the constructor function for an object using the instanceof operator.



So you could do the following:



console.log(x instanceof T.Q.W.C);


OR



console.log(x.constructor === T.Q.W.C);

[#90762] Friday, August 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ingridmikaylam

Total Points: 93
Total Questions: 81
Total Answers: 105

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;