Home > Web Front-end > JS Tutorial > body text

Instructions for using javascript instanceof and typeof_Basic knowledge

WBOY
Release: 2016-05-16 18:36:57
Original
925 people have browsed it

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) it will An error occurs. 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 have 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 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 very similar. .

The instanceof operator in JavaScript returns a Boolean value, indicating whether the object is an instance of a specific class.
Usage:
result = object instanceof class
where result is a required option. Any variable.
object is required. Any object expression.
class is required. Any defined object class.

Explanation
If object is an instance of class, the instanceof operator returns true. Returns false if object is not an instance of the specified class, or if object is null.

Instanceof operator in JavaScript
The following example illustrates the usage of instanceof operator.

Copy code The code is as follows:

function objTest(obj){
var i, t, s = ""; // Create variable.
t = new Array(); // Create an array.
t["Date"] = Date; // Fill the array.
t["Object"] = Object;
t["Array"] = Array;
for (i in t)
{
if (obj instanceof t[i]) / / Check the class of obj.
{
s = "obj is an instance of " i "n";
}
else
{
s = "obj is not an instance of " i "n" ;
}
}
return(s); // Return a string.
}

var obj = new Date();
response.write(objTest(obj));
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template