Home >Web Front-end >JS Tutorial >Summary of the difference between typeof and instanceof in JS_javascript skills

Summary of the difference between typeof and instanceof in JS_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:15:27925browse

In JavaScript, typeof and instanceof are often used to determine whether a variable is empty or what type it is. But there are still differences between them:

typeof

typeof is a unary operation, placed before an operand, and the operand can be of any type.

The return value is a string describing the type of the operand. typeof generally can only return the following results:

number, boolean, string, function, object, undefined. We can use typeof to get whether a variable exists, such as if(typeof a!="undefined"){alert("ok")} instead of using if(a) because if a does not exist (not declared ), an error will occur. For special objects such as Array and Null, typeof will always return object. This is the limitation of typeof.

instanceof

instance: instance, example

a instanceof b?alert("true"):alert("false"); //a is an instance of b? True:False

instanceof is used to determine whether a variable is an instance of an object, such as var a=new Array();alert(a instanceof Array);
will return true, and alert(a instanceof Object) will also return true ;This is because Array is a subclass of object
. Another example: function test(){};var a=new test();alert(a instanceof test) will return

Speaking of instanceof, we have to insert one more problem, which is the arguments of function. We may all think that arguments are an
Array, but if you use instanceof to test, you will find that arguments are not an Array object, even though it looks very similar. .

Also:

Test var a=new Array();if (a instanceof Object) alert('Y');else alert('N');

Got 'Y'

But if (window instanceof Object) alert('Y');else alert('N');

Got 'N'

So, the object tested by instanceof here refers to the object in js syntax, not the dom model object.

There will be some differences using typeof

alert(typeof(window)) will get object

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