您好,欢迎访问一九零五行业门户网

JavaScript instanceof 的使用方法示例介绍_基础知识

在 javascript 中,判断一个变量的类型尝尝会用 typeof 运算符,在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 “object”。这就需要用到instanceof来检测某个对象是不是另一个对象的实例。
通常来讲,使用 instanceof 就是判断一个实例是否属于某种类型。
另外,更重的一点是 instanceof 可以在继承关系中用来判断一个实例是否属于它的父类型。
复制代码 代码如下:
// 判断 foo 是否是 foo 类的实例 , 并且是否是其父类型的实例function aoo(){}
function foo(){}
foo.prototype = new aoo();//javascript 原型继承
var foo = new foo();
console.log(foo instanceof foo)//true
console.log(foo instanceof aoo)//true
上面的代码中是判断了一层继承关系中的父类,在多层继承关系中,instanceof 运算符同样适用。
instanceof 复杂用法
复制代码 代码如下:
function cat(){}
cat.prototype = {}
function dog(){}
dog.prototype ={}
var dog1 = new dog();
alert(dog1 instanceof dog);//true
alert(dog1 instanceof object);//true
dog.prototype = cat.prototype;
alert(dog1 instanceof dog);//false
alert(dog1 instanceof cat);//false
alert(dog1 instanceof object);//true;
var dog2= new dog();
alert(dog2 instanceof dog);//true
alert(dog2 instanceof cat);//true
alert(dog2 instanceof object);//true
dog.prototype = null;
var dog3 = new dog();
alert(dog3 instanceof cat);//false
alert(dog3 instanceof object);//true
alert(dog3 instanceof dog);//error
要想从根本上了解 instanceof 的奥秘,需要从两个方面着手:1,语言规范中是如何定义这个运算符的。2,javascript 原型继承机。大家感兴趣的可以去查看相关资料。
其它类似信息

推荐信息