In JavaScript, typeof and instanceof are often used to determine whether a variable is empty or what type it is. But there is a difference between them:
typeof
TypeOf is a unary operation, which can be any type of operation before it is placed in one op-count.
The return value is a string that describes 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 the existence of a variable, such as if (typeof a!= "undefined") {alert ("OK")}, and not to use if (a) because if a does not exist (not declared) there will be an error, for the Array,null Such special objects use TypeOf to return object, which is the limitation of TypeOf.
instanceof
Instance: examples, examples
A instanceof B?alert ("true"): Alert ("false"); A is an example of B? True: false
Instanceof is used to determine whether a variable is an instance of an object, such as the Var a=new array (); alert (a instanceof array); Returns True, while alert (a Instanceof object) returns True, because the Array is a subclass of Object. Another example: function Test () {};var a=new test (); alert (a instanceof test) returns
When it comes to instanceof, we're going to insert one more question, which is the arguments of the function, and we all probably think that arguments is an array, but if you use instaceof to test, you'll find that arguments is not an array object, though it looks like it.
Other than that:
Test var a=new Array (); if (a instanceof Object) alert (' Y '); else alert (' N ');
Get ' Y '
But if (window instanceof Object) alert (' Y '); else alert (' N ');
Get ' N '
So, the object of the instanceof test here refers to the object in the JS syntax, not the DOM model object.
There are some differences between using typeof
Alert (typeof (Window)) Gets object
Thank you for reading, I hope to help you, thank you for your support for this site!