Home  >  Article  >  Web Front-end  >  Introduction to typeof and instanceof in javascript_Basic knowledge

Introduction to typeof and instanceof in javascript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:47:17947browse

typeof is used to detect the data type of a given variable (also called basic type, basic data type. Including undefined, boolean, string, number, object, function)
var message = "so easy";
alert(typeof message); //"string"
alert(typeof 12); //"number"

You can remember it like this: typeof is used to judge "variables" that are not created with new.

instanceof is used to detect the type of an object (also called a reference type. It includes Object, Array, Date, RegExp, Function, and basic packaging types (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 object and belongs to the Number reference type (all reference types inherit from the Object reference type).

You can remember it like this: instanceof detects "objects" created with new. "Variables" that are not created through new do not belong to any reference type. Using typeof to detect "objects" created with new always returns "object reference type".

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn