Comparison of Three Types of JavaScript detection typeof, instanceof, and toString

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.