Introduction to typeof and instanceof in javascript

Source: Internet
Author: User

Typeof is used to detect the Data Type of a given variable (also called Basic type, basic data type. Contains undefined, boolean, string, number, object, function)
Var message = "so easy ";
Alert (typeof message); // "string"
Alert (typeof 12); // "number"

You can remember this: typeof is used to determine whether the "variable" created with new is used ".

Instanceof is used to detect the object type (also called the reference type. Including Object, Array, Date, RegExp, Function, basic packaging type (including Boolean, Number, String ))
Var numberObject = new Number (10 );
Var numberValue = 10;
Alert (typeof numberObject); // "object"
Alert (typeof numberValue); // "number"
Alert (numberObject instanceof Number); // true
Alert (numberValue instanceof Number); // false
NumberValue is the basic data type of number and does not belong to any reference type.
NumberObject is the basic data type of the object and belongs to the Number reference type (all reference types are inherited from the Object reference type ).

You can remember this: instanceof detects "objects" created with new ". The "variable" not created through new does not belong to any reference type. The typeof method is used to detect that "object Reference Type" is always returned for "object" created with new ".

The isPrototypeOf () method is used to detect the relationship between the prototype and the instance. Instanceof can also be detected. Any prototype that has appeared in the prototype chain can be said to be the prototype of the Instance derived from the prototype chain.
Var person = new Person (); // the inheritance of Person and Object
Alert (Person. prototype. isPrototypeOf (person); // true
Alert (Object. prototype. isPrototypeOf (person); // true

 

Related Article

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.