I have used instanceof and typeof occasionally before, especially typeof, and I have used it more. Today, I have studied ext source code and used instanceof in many places. I suddenly felt that they were somewhat similar but they should be different. I read some articles online and have a certain understanding of the relationship between them.
instanceof and typeof can be used to determine whether a variable is empty or what type of variable.
typeof is used to obtain the type of a variable. typeof can generally 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 (not declared), an error will occur. For special objects such as Array, Null, etc., you will return object. 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 need to choose to 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 a subclass of object. For example: function test(){};var a=new test();alert(a instanceof test) will return true.
When it comes to instanceof, we need to insert one more problem, that is, function arguments. We may all think that arguments are an Array, but if we use instanceof to test, we will find that arguments are not an Array object, although they look very similar.