JavaScript method of determining the data type 6


typeof

typeof is an operator that the right side with a monadic expression, and returns the data type of the expression. The results returned are represented by the type of string (all lowercase letters) in the form of
typeof although can be used, but if you use it to view or null type of the array, will be overturned oh
because typeof only return number, boolean, string, undefined , object, function, ES as well as symbol
Here Insert Picture Description
Here Insert Picture Description

Object.prototype.toString…

toString () is the prototype Object methods that, when invoked, return the current default object [[Class]]. For Object object, direct call toString () can return [object Object], while for other objects, you need to call in order to return the correct type information call.
Object.prototype.toString.call(arr/obj)
Returns a string directly show what type of correspondence, no pressure, is perfect
Here Insert Picture Description
since .call so that, then I tried it and bind apply, the discovery Ye Hao. Rest assured!
Object.prototype.toString.apply(arr/obj)
Object.prototype.toString.bind(arr/obj)()
Here Insert Picture Description

instanceof

A instanceof determines whether to Example B, the expression is: A instanceof B, if A is Example B, then returns true, otherwise returns false. instanceof prototype testing, whether there is an internal mechanism by determining the type of the object prototype prototype chain.
This is very sad, very useless.

  1. Because the return value is a Boolean value. You can only rely on their own guess, and then test yourself is not a type. Or Object.prototype.toString.xxx easy to use, direct people to return string, to see more intuitive and accurate.
  2. Because it can not determine the basic data types, you see all six basic data types overturned.
    If you ask me why I do not write c instanceof null d instanceof undefined, because writing so will complain!
    Here Insert Picture Description

constructor

When a function is defined, JS Prototype prototype engine to add, and then adding a constructor property on the prototype. Constructor property points to the function itself.
This is super invincible tasteless , null and undefined direct encounters an error
Here Insert Picture DescriptionHere Insert Picture Description
, but fortunately, other data types can judge
Here Insert Picture Description


I am a Luo Lian, today is the day it hard

Published 131 original articles · won praise 451 · views 540 000 +

Guess you like

Origin blog.csdn.net/qq_36667170/article/details/105152982