Problems and discussion of instanceof use in Javascript

Source: Internet
Author: User

First on the code:
var a = 10;
Alert (a instanceof number);//falseWhy is it false here?
Alert (a instanceof String);//false
Alert (a instanceof Object);//falseWhy is it false here?
Alert (typeof a = = ' number ');//true

var a = [' 1 ', ' a '];
Alert (a instanceof Array);//true
Alert (a instanceof Object);//true
Alert (typeof a = = ' object ');//true

var a = ' a ';
Alert (a instanceof String);//falseWhy is it false here?
Alert (a instanceof Object);//falseWhy is it false here?
Alert (typeof A = = ' string ');//true

What I can't figure out is: Why is it false? I've got the answers, and the answer is
Instanceof is used to determine whether an instance of an object is used, and typeof to determine the data type. But this answer is not enough to explain the problem, so come up and ask me, please teach me, thank you!

========================== Ornate Split Line ==========================================


Ask yourself the answer:
A specific number, 10, which can be considered to be of type #, can also be considered an instance of number in an object type, but this makes the problem of classification conflict, which is number type and object type (its subclass number type), therefore, instanceof to exclude the types specified in the data types that are already defined, that is, only for custom types.
In addition, for arrays with only the concept of class array, there is no array data type, typeof can only return the object data type, so for arrays it is possible to use instanceof.

In summary: There is no need to tangle with JavaScript syntax, because it is a weak type of variable language, it is really not rigorous.


This article from the "7889902" blog, reproduced please contact the author!

Problems and discussion of instanceof use in Javascript

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.