您的位置:首页 > Web前端 > JavaScript

JavaScript instanceof 的使用方法

2013-10-23 13:07 633 查看
在 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 原型继承机。大家感兴趣的可以去查看相关资料。

 

参考资料:  JavaScript instanceof 的用法    http://www.studyofnet.com/news/175.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息