实例
左侧(LHS)操作数是要测试到右侧(RHS)操作数的实际对象,右侧对象是类的实际构造函数。基本定义是:
Checks the current object and returns true if the objectis of the specified object type.
这是直接从Mozilla开发人员网站获取的示例:
var color1 = new String("green");color1 instanceof String; // returns truevar color2 = "coral"; //no type specifiedcolor2 instanceof String; // returns false (color2 is not a String object)值得一提的是
instanceof,如果对象继承自类的原型,则其值为true:
var p = new Person("Jon");p instanceof Person这是
p instanceof Person是因为真正
p的继承
Person.prototype。
根据OP的要求
我添加了一个带有示例代码和解释的小示例。
声明变量时,可以为其指定特定类型。
例如:
int i;float f;Customer c;
上面显示一些变量,即
i,
f和
c。这些类型是
integer,
float和用户定义的
Customer数据类型。诸如此类的类型可以适用于任何语言,而不仅仅是Javascript。但是,使用Javascript声明变量时,您不会显式定义类型
varx,x可能是数字/字符串/用户定义的数据类型。因此,
instanceof它执行的操作是检查对象以查看其是否为指定的类型,因此从上面开始
Customer我们可以执行以下操作:
var c = new Customer();c instanceof Customer; //Returns true as c is just a customerc instanceof String; //Returns false as c is not a string, it's a customer silly!
上面我们已经看到了
c用type声明的
Customer。我们已经对其进行了更新,并检查了它是否为类型
Customer。当然,它返回true。然后,仍然使用该
Customer对象,检查它是否为
String。不,绝对不是
String我们更新的
Customer对象而不是
String对象。在这种情况下,它返回false。
真的就是这么简单!



