The most accurate way to check JS object's type?

后端 未结 9 1019
借酒劲吻你
借酒劲吻你 2020-12-04 05:33

The typeof operator doesn\'t really help us to find the real type of an object.

I\'ve already seen the following code :

Object.prototyp         


        
9条回答
  •  渐次进展
    2020-12-04 05:45

    I'd argue that most of the solutions shown here suffer from being over-engineerd. Probably the most simple way to check if a value is of type [object Object] is to check against the .constructor property of it:

    function isObject (a) { return a != null && a.constructor === Object; }
    

    or even shorter with arrow-functions:

    const isObject = a => a != null && a.constructor === Object;
    

    The a != null part is necessary because one might pass in null or undefined and you cannot extract a constructor property from either of these.

    It works with any object created via:

    • the Object constructor
    • literals {}

    Another neat feature of it, is it's ability to give correct reports for custom classes which make use of Symbol.toStringTag. For example:

    class MimicObject {
      get [Symbol.toStringTag]() {
        return 'Object';
      }
    }
    

    The problem here is that when calling Object.prototype.toString on an instance of it, the false report [object Object] will be returned:

    let fakeObj = new MimicObject();
    Object.prototype.toString.call(fakeObj); // -> [object Object]
    

    But checking against the constructor gives a correct result:

    let fakeObj = new MimicObject();
    fakeObj.constructor === Object; // -> false
    

提交回复
热议问题