JavaScript中instanceof运算符的使用示例


本文向大家介绍JavaScript中instanceof运算符的使用示例,包括了JavaScript中instanceof运算符的使用示例的使用技巧和注意事项,需要的朋友参考一下

instanceof运算符可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上。

实例一:普遍用法

A instanceof B :检测B.prototype是否存在于参数A的原型链上.

function Ben() {

}
var ben = new Ben();
console.log(ben instanceof Ben);//true

实例二:继承中判断实例是否属于它的父类

function Ben_parent() {}

function Ben_son() {}

Ben_son.prototype = new Ben_parent();//原型继承

var ben_son = new Ben_son();

console.log(ben_son instanceof Ben_son);//true

console.log(ben_son instanceof Ben_parent);//true

实例三:表明String对象和Date对象都属于Object类型

下面的代码使用了instanceof来证明:String和Date对象同时也属于Object类型。

var simpleStr = "This is a simple string"; 
var myString = new String();
var newStr  = new String("String created with constructor");
var myDate  = new Date();
var myObj   = {};

simpleStr instanceof String; // returns false, 检查原型链会找到 undefined
myString instanceof String; // returns true
newStr  instanceof String; // returns true
myString instanceof Object; // returns true

myObj instanceof Object;  // returns true, despite an undefined prototype
({}) instanceof Object;  // returns true, 同上

myString instanceof Date;  // returns false

myDate instanceof Date;   // returns true
myDate instanceof Object;  // returns true
myDate instanceof String;  // returns false

实例四:演示mycar属于Car类型的同时又属于Object类型

下面的代码创建了一个类型Car,以及该类型的对象实例mycar. instanceof运算符表明了这个mycar对象既属于Car类型,又属于Object类型。

function Car(make, model, year) {
 this.make = make;
 this.model = model;
 this.year = year;
}
var mycar = new Car("Honda", "Accord", 1998);
var a = mycar instanceof Car;  // 返回 true
var b = mycar instanceof Object; // 返回 true

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#yiidian.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。