instanceof(的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.
(左侧(LHS)操作数是被测试到右侧(RHS)操作数的实际对象,该操作数是类的实际构造函数。)
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 :
(以下是一些很好的示例 ,这是一个直接从Mozilla开发者网站获取的示例:)
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:
(值得一提的是,如果对象继承自classe的原型,则instanceof
计算结果为true:)
var p = new Person("Jon");
p instanceof Person
That is p instanceof Person
is true since p
inherits from Person.prototype
.
(这是p instanceof Person
是真的,因为p
继承自Person.prototype
。)
Per the OP's request(根据OP的要求)
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
.
(以上显示了一些变量,即i
, f
和c
。)
The types are integer
, float
and a user defined Customer
data type.(类型是integer
, float
和用户定义的Customer
数据类型。)
Types such as the above could be for any language, not just JavaScript.(上述类型可以用于任何语言,而不仅仅是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.(但是,使用JavaScript声明变量时未明确定义类型, var x
,x可以是数字/字符串/用户定义的数据类型。)
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:(那么instanceof
做的是它检查对象以查看它是否是指定的类型,从上面获取我们可以做的Customer
对象:)
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
.
(上面我们已经看到c
是用Customer
类型声明的。)
We've new'd it and checked whether it is of type Customer
or not.(我们已经新了,并检查它是否属于Customer
类型。)
Sure is, it returns true.(当然,它返回true。)
Then still using the Customer
object we check if it is a String
.(然后仍然使用Customer
对象检查它是否是String
。)
Nope, definitely not a String
we newed a Customer
object not a String
object.(不,绝对不是String
我们新建了Customer
对象而不是String
对象。)
In this case, it returns false.(在这种情况下,它返回false。)
It really is that simple!
(真的很简单!)