Home > Article > Web Front-end > Determine whether to use what operator for a jquery object
Use the "instanceof" operator to determine whether an object is a jquery object; the instanceof operator can determine whether an object is a specified data type. The syntax is "if (object variable instanceof jQuery) {//It is a jQ object }else{//Not}".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Use the "instanceof" operator to determine whether an object is a jquery object.
instanceof
: Determine whether an object is a certain data type, or whether a variable is an instance of an object; return boolean type
Example :
var obj = $("div"); if(obj instanceof jQuery){ alert("这是一个jQuery对象"); }else{ alert("这是一个其它对象") }
Explanation: Instanceof and typeof can be used to determine whether a variable is empty or what type of variable it is.
typeof: 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 (Not declared) will cause an error. Using typeof for special objects such as Array and Null will always 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 must choose to use instanceof
.
instanceof is used to determine whether a variable is an instance of an object, such as the arguments of
var a=new Array(); alert(a instanceof Array); //会返回true alert(a instanceof Object) //也会返回true;这是因为Array是object的子类 function test(){}; var a=new test(); alert(a instanceof test) //会返回true
function. We all may think that arguments are an Array, but if you use Instaceof tests and finds that arguments is not an Array object, although it looks similar.
Test
var a=new Array(); if (a instanceof Object) alert('Y'); else alert('N'); //Y
But:
if (window instanceof Object) alert('Y'); else alert('N'); //N
So, the object tested by instanceof here refers to the object in js syntax, not the dom model object.
There will be some differences when using typeof
alert(typeof(window) //会得 object
[Recommended learning: jQuery video tutorial, web front-end development]
The above is the detailed content of Determine whether to use what operator for a jquery object. For more information, please follow other related articles on the PHP Chinese website!