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.