JavaScript中instanceof运算符的使用示例
instanceof运算符可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上。
实例一:普遍用法
AinstanceofB:检测B.prototype是否存在于参数A的原型链上.
functionBen(){
}
varben=newBen();
console.log(beninstanceofBen);//true
实例二:继承中判断实例是否属于它的父类
functionBen_parent(){}
functionBen_son(){}
Ben_son.prototype=newBen_parent();//原型继承
varben_son=newBen_son();
console.log(ben_soninstanceofBen_son);//true
console.log(ben_soninstanceofBen_parent);//true
实例三:表明String对象和Date对象都属于Object类型
下面的代码使用了instanceof来证明:String和Date对象同时也属于Object类型。
varsimpleStr="Thisisasimplestring";
varmyString=newString();
varnewStr=newString("Stringcreatedwithconstructor");
varmyDate=newDate();
varmyObj={};
simpleStrinstanceofString;//returnsfalse,检查原型链会找到undefined
myStringinstanceofString;//returnstrue
newStrinstanceofString;//returnstrue
myStringinstanceofObject;//returnstrue
myObjinstanceofObject;//returnstrue,despiteanundefinedprototype
({})instanceofObject;//returnstrue,同上
myStringinstanceofDate;//returnsfalse
myDateinstanceofDate;//returnstrue
myDateinstanceofObject;//returnstrue
myDateinstanceofString;//returnsfalse
实例四:演示mycar属于Car类型的同时又属于Object类型
下面的代码创建了一个类型Car,以及该类型的对象实例mycar.instanceof运算符表明了这个mycar对象既属于Car类型,又属于Object类型。
functionCar(make,model,year){
this.make=make;
this.model=model;
this.year=year;
}
varmycar=newCar("Honda","Accord",1998);
vara=mycarinstanceofCar;//返回true
varb=mycarinstanceofObject;//返回true