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
热门推荐
7 带清的简短祝福语
10 宝子生日祝福语简短
11 送外卖祝福语大全简短
12 婆婆生日祝福语短语简短
13 分手毕业祝福语简短女生
14 新疆新年祝福语大全简短
15 文艺结婚祝福语短语简短
16 写给老师祝福语简短大学
17 简短56岁生日祝福语
18 朋友花篮开业祝福语简短