What is the instanceof operator in JavaScript?
The instanceof
keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.
instanceof
The Left Hand Side (LHS) operand is the actual object being tested to the Right Hand Side (RHS) operand which is the actual constructor of a class. The basic definition is:
Checks the current object and returns true if the object
is of the specified object type.
Here are some good examples and here is an example taken directly from Mozilla's developer site:
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)
One thing worth mentioning is instanceof
evaluates to true if the object inherits from the classe's prototype:
var p = new Person("Jon");
p instanceof Person
That is p instanceof Person
is true since p
inherits from Person.prototype
.
Per the OP's request
I've added a small example with some sample code and an explanation.
When you declare a variable you give it a specific type.
For instance:
int i;
float f;
Customer c;
The above show you some variables, namely i
, f
, and c
. The types are integer
, float
and a user defined Customer
data type. Types such as the above could be for any language, not just JavaScript. However, with JavaScript when you declare a variable you don't explicitly define a type, var x
, x could be a number / string / a user defined data type. So what instanceof
does is it checks the object to see if it is of the type specified so from above taking the Customer
object we could do:
var c = new Customer();
c instanceof Customer; //Returns true as c is just a customer
c instanceof String; //Returns false as c is not a string, it's a customer silly!
Above we've seen that c
was declared with the type Customer
. We've new'd it and checked whether it is of type Customer
or not. Sure is, it returns true. Then still using the Customer
object we check if it is a String
. Nope, definitely not a String
we newed a Customer
object not a String
object. In this case, it returns false.
It really is that simple!
There's an important facet to instanceof that does not seem to be covered in any of the comments thus far: inheritance. A variable being evaluated by use of instanceof could return true for multiple "types" due to prototypal inheritance.
For example, let's define a type and a subtype:
function Foo(){ //a Foo constructor
//assign some props
return this;
}
function SubFoo(){ //a SubFoo constructor
Foo.call( this ); //inherit static props
//assign some new props
return this;
}
SubFoo.prototype = new Foo(); // Inherit prototype
Now that we have a couple of "classes" lets make some instances, and find out what they're instances of:
var
foo = new Foo()
, subfoo = new SubFoo()
;
alert(
"Q: Is foo an instance of Foo? "
+ "A: " + ( foo instanceof Foo )
); // -> true
alert(
"Q: Is foo an instance of SubFoo? "
+ "A: " + ( foo instanceof SubFoo )
); // -> false
alert(
"Q: Is subfoo an instance of Foo? "
+ "A: " + ( subfoo instanceof Foo )
); // -> true
alert(
"Q: Is subfoo an instance of SubFoo? "
+ "A: " + ( subfoo instanceof SubFoo )
); // -> true
alert(
"Q: Is subfoo an instance of Object? "
+ "A: " + ( subfoo instanceof Object )
); // -> true
See that last line? All "new" calls to a function return an object that inherits from Object. This holds true even when using object creation shorthand:
alert(
"Q: Is {} an instance of Object? "
+ "A: " + ( {} instanceof Object )
); // -> true
And what about the "class" definitions themselves? What are they instances of?
alert(
"Q: Is Foo an instance of Object? "
+ "A:" + ( Foo instanceof Object)
); // -> true
alert(
"Q: Is Foo an instance of Function? "
+ "A:" + ( Foo instanceof Function)
); // -> true
I feel that understanding that any object can be an instance of MULTIPLE types is important, since you my (incorrectly) assume that you could differentiate between, say and object and a function by use of instanceof
. As this last example clearly shows a function is an object.
This is also important if you are using any inheritance patterns and want to confirm the progeny of an object by methods other than duck-typing.
Hope that helps anyone exploring instanceof
.
The other answers here are correct, but they don't get into how instanceof
actually works, which may be of interest to some language lawyers out there.
Every object in JavaScript has a prototype, accessible through the __proto__
property. Functions also have a prototype
property, which is the initial __proto__
for any objects created by them. When a function is created, it is given a unique object for prototype
. The instanceof
operator uses this uniqueness to give you an answer. Here's what instanceof
might look like if you wrote it as a function.
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
This is basically paraphrasing ECMA-262 edition 5.1 (also known as ES5), section 15.3.5.3.
Note that you can reassign any object to a function's prototype
property, and you can reassign an object's __proto__
property after it is constructed. This will give you some interesting results:
function F() { }
function G() { }
var p = {};
F.prototype = p;
G.prototype = p;
var f = new F();
var g = new G();
f instanceof F; // returns true
f instanceof G; // returns true
g instanceof F; // returns true
g instanceof G; // returns true
F.prototype = {};
f instanceof F; // returns false
g.__proto__ = {};
g instanceof G; // returns false
链接地址: http://www.djcxy.com/p/6978.html
上一篇: 当一个类被子类化时如何运行代码?