44

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.

4
  • 2
    I think you have to rephrase the question. x is an instance and yes, using new is pretty reliable to get an instance. Maybe you are looking for instancof, to get the type of the instance? developer.mozilla.org/en/JavaScript/Reference/Operators/Special/… Commented Aug 7, 2011 at 16:02
  • 1
    TL;DR: In regards to the actual question in the title ("get type/instance name"), use Object.getPrototypeOf(instanceName).constructor to safely access (due to immutability) the object's constructor function, which will be its actual JS type (e.g. the type of its class, or just Object, Function, Number, String, etc.), and then use theType.name to get the string name of said type. For unsafe access, you could simply use instanceName.constructor. Commented Mar 29, 2023 at 2:28
  • As for the question itself, the example code is sort of poorly framed (though this is not a criticism as obviously one can't be expected to know how to perfectly ask something they're learning about). I think the best you're gonna be able to do with that code is just check for things using instanceof like the other comments/answers describe. More likely one would be using classes with extends for inheritance. Commented Mar 29, 2023 at 2:39
  • In that case, use the method I just provided; or, if you want the base class type, you can put a function inside the class (can't be set on the .prototype) and then use super.constructor instead. Note that here you can't use Object.getPrototypeOf(super), because super is just a JS keyword. You could then for instance return the type from the function. It seems that you can only ever access 1 super, the immediate parent, though... Another approach would be to store this.constructor or super.constructor as a property of each class............................................ Commented Mar 29, 2023 at 2:49

6 Answers 6

79

Only tested on Chrome:

function FooBar() {

}

var foobar = new FooBar();

console.log(foobar.constructor.name);  // Prints 'FooBar'
Sign up to request clarification or add additional context in comments.

1 Comment

Same with Firefox 102.0. I believe it has worked this way in Firefox for quite some time.
40

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);

1 Comment

Next answer answers the asked question.
12

In case anyone is still reading this in 2017:

Be careful about using obj.constructor, as it is not an immutable property.

The instanceof operator is generally more reliable. You can also use Object.getPrototypeOf(obj):

var arr = [];
arr instanceof Array; // true
Object.getPrototypeOf(arr); // Array [  ]
Object.getPrototypeOf(arr) === Array.prototype; // true

See this useful document on the topic:

https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md

2 Comments

Note: Let's say elem is a <span> (HTMLSpanElement), then elem.isPrototypeOf(Element) => false whereas elem instanceof Element => true
See my comments on the question for more regarding this approach...
4

I had some trouble with this, the solution was:

String(x.constructor) === String(T.Q.W.C)

Comments

0

You can do :

    get(){ // Method
        for ( var nameOfVariable in window ) 
            if (eval(nameOfVariable +"=== this")) return nameOfVariable;// true if variable name is instace of this
        return "";            
    }

Comments

-1

Be aware that contructor.name cannot be used with minifying (it will be an empty string) - only instanceof can be used here.

1 Comment

That may have something to do with your build/bundler/optimizer configuration, an instance of an object created with var obj = new Template() will have a obj.constructor.name property available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.