Home > Web Front-end > JS Tutorial > body text

A brief discussion on instanceof and typeof_javascript techniques in javascript

WBOY
Release: 2016-05-16 16:12:39
Original
1175 people have browsed it

For instanceof and typeof, I have occasionally used them before, especially typeof, which is relatively more used. Today, when I studied the ext source code, instanceof was used in many places. I suddenly felt that they are somewhat similar, but they should also be included. Differences, I read some articles online and have a certain understanding of the relationship between them.

Instanceof and typeof can both be used to determine whether a variable is empty or what type of variable it is.
Typeof is used to obtain the type of a variable. 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"){}, instead of using if(a) because if a does not exist (undeclared), an error will occur. For Array, Null When using typeof for special objects, object will always be returned. This is the limitation of typeof.

If we want to get whether an object is an array, or determine whether a variable is an instance of an object, we must use instanceof. instanceof is used to determine whether a variable is an instance of an object. For example, 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 subclass of object. Another example: function test(){};var a=new test();alert(a instanceof test) will return true.

When it comes to 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 similar.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!