javascript get type/instance name

后端 未结 5 1909
一个人的身影
一个人的身影 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: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

提交回复
热议问题