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.
Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.
Get and print the type of an object: type() type() returns the type of an object. You can use this to get and print the type of a variable and a literal like typeof in other programming languages. The return value of type() is type object such as str or int .
Access the name property on the object's constructor to get the class name of the object, e.g. obj.constructor.name . The constructor property returns a reference to the constructor function that created the instance object. Copied! We accessed the name property on the Object.
The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.
Only tested on Chrome:
function FooBar() { } var foobar = new FooBar(); console.log(foobar.constructor.name); // Prints 'FooBar'
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With