This article briefly introduces the information about instanceof and typeof in javascript. For more information, see instanceof and typeof, in particular, typeof uses more and more objects. Today we are studying ext source code, and instanceof is used in many places. I suddenly think the two of them are similar, but they should have their differences. I read some articles online, have a certain understanding of the relationship between them.
Both instanceof and typeof can be used to determine whether a variable is null or of any type.
Typeof is used to obtain the type of a variable. Generally, typeof can only return the following results: number, boolean, string, function, object, undefined. We can use typeof to obtain whether a variable exists, such as if (typeof! = "Undefined") {}, instead of using if (a) because if a does not exist (not declared), an error occurs. For Array, null and other special objects use typeof to return all objects, which is the limitation of typeof.
If you want to obtain whether an object is an array or determine whether a variable is an instance of an object, you must use instanceof. Instanceof is an instance used to determine whether a variable is an Object, such as var a = new Array (); alert (a instanceof Array); true is returned, and alert (a instanceof Object) true is also returned because Array is a subclass of the object. For example, function test () {}; var a = new test (); alert (a instanceof test) returns true.
When talking about instanceof, We need to insert another question: function arguments. We may all think that arguments is an Array. However, if we use instaceof to test, we will find that arguments is not an Array object, although it looks very similar.