Comparison of Three Types of JavaScript detection typeof, instanceof, and toString
Comparison of Three Types of JavaScript detection typeof, instanceof, and toString
1. typeof
Typeof is an operator of js. It is of almost no use in type detection.
Typeof returns a string of the expression data type. The returned result is of the basic data type in javascript, including number, boolean, string, object, undefined, and function.
That is to say, typeof can only return these types. For our custom object, it will only return the object, and the function in the actual application is approximately equal to zero.
In addition, typeof may have compatibility issues in different browsers, such as recognizing the function type as an object.
2. instanceof
The instanceof operator uses another method to determine the object type: prototype chain. For example, if a instanceof B can find B on the prototype chain of object a, it is considered that a is an object of type B.
It looks beautiful, but there is a defect: If a page has multiple frameworks, that is, multiple global environments, then I define an Array in framework, then, use instanceof in framework B to judge. Therefore, the array in framework B cannot be found in the prototype chain of the array, and the array is not an array.
3. toString
Use the Object. prototype. toString. call (value) method to call the Object and obtain the Object's constructor name. It can solve the cross-framework problem of instanceof. The disadvantage is that it only returns [object Object] for user-defined types.
This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151260.htm