javascript get type/instance name

后端 未结 5 1868
一个人的身影
一个人的身影 2021-02-07 01:06

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

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

var         


        
相关标签:
5条回答
  • 2021-02-07 01:18

    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);
    
    0 讨论(0)
  • 2021-02-07 01:29

    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

    0 讨论(0)
  • 2021-02-07 01:36

    I had some trouble with this, the solution was:

    String(x.constructor) === String(T.Q.W.C)
    
    0 讨论(0)
  • 2021-02-07 01:45

    Only tested on Chrome:

    function FooBar() {
    
    }
    
    var foobar = new FooBar();
    
    console.log(foobar.constructor.name);  // Prints 'FooBar'
    
    0 讨论(0)
  • 2021-02-07 01:45

    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 "";            
        }
    
    0 讨论(0)
提交回复
热议问题