Introduction to typeof and Instanceof in JavaScript _ basics

Source: Internet
Author: User

typeof is used to detect the data type of a given variable (also called the basic type, the base data type.) Contains Undefined, Boolean, string, number, object, function
var message = ' So easy ';
Alert (typeof message); "String"
Alert (typeof 12); "Number"

Memory: typeof is used to judge "variables" that are not created with new.

Instanceof is used to detect the type of an object (also referred to as a reference type.) Contains object, Array, Date, RegExp, Function, base wrapper 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 number underlying data type and does not belong to any reference type.
Numberobject is the object underlying data type, which belongs to the number reference type (all reference types inherit from the object reference type).

You can remember this: instanceof detects "objects" created with new. "Variables" that are not created by new are not part of any reference type. Using typeof to detect "objects" created with new always returns an object reference type.

The isPrototypeOf () method is used to detect the relationship between the prototype and the instance. Instanceof can also be detected. As long as the prototype in the prototype chain, can be said to be the prototype chain derived from the prototype of the instance.
var person = new person (); Person inheritance and Object
Alert (Person.prototype.isPrototypeOf (person)); True
Alert (Object.prototype.isPrototypeOf (person)); True

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.