What are the methods of Javascript data type detection

  1. In typeof,
    array, object, and null will be judged as object, and other judgments are correct.
    typeof

  2. instanceof
    instanceof can correctly determine the type of the object, and its internal operation mechanism is to determine whether the prototype of the type can be found in its prototype chain. It can be seen that instanceof can only correctly judge the reference data type, but not the basic data type. The instanceof operator can be used to test whether an object has a constructor's prototype property in its prototype chain.
    instanceof

  3. constructor constructor
    The constructor has two functions, one is to judge the type of data, and the other is to access the constructor of the object instance through the constructor object. It should be noted that if an object is created to change its prototype, the constructor cannot be used to determine the data type:
    constructor

  4. Object.prototype.toString.call()
    Object.prototype.toString.call() uses the prototype method
    toString of the Object object to determine the data type:
    toString

The same is to call the toString method of the detection object obj, the result of obj.toString() is different from the result of Object.prototype.toString.call(obj), why?

This is because toString is the prototype method of Object, and types such as Array and function are instances of Object, and the toString method is rewritten. When different object types call the toString method, according to the knowledge of the prototype chain, the corresponding rewritten toString method is called (the function type returns a string whose content is the function body, and the Array type returns a string composed of elements...), while It will not call the prototype toString method on Object (returns the specific type of the object), so the object type cannot be obtained by using obj.toString(), and obj can only be converted to a string type; , the toString method on the Object prototype should be called.

Guess you like

Origin blog.csdn.net/weixin_45753871/article/details/127322975
Recommended