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

js如何判断一个对象是array ,instanceof 是基于什么实现的呢?

2016-06-08 14:42 816 查看


typeof 操作符

对于Function, String, Number ,Undefined 等几种类型的对象来说,他完全可以胜任,但是为Array时

var  arr = [1,2,3,4,5];
console.log(typeof arr)


你会得到一个object 的答案。


instanceof 操作符

Js中instanceof运算符会返回一个 Boolean 值,指出对象是否是特定类的一个实例。 如下
var arr=["1","2","3","4","5"];
console.log(arr instanceof Array);


你会得到一个true.这样你就可以得到你想要的结果了,

之前有个同事面试的时候问了这个问题,但是面试官继续问了一个她一个问题,instanceof 这个操作符的原理是什么,我想这样这里有必要说一下。

instanceof 检测一个对象A是不是另一个对象B的实例的原理是:查看对象B的prototype指向的对象是否在对象A的[[prototype]]链上。如果在,则返回true,如果不在则返回false。不过有一个特殊的情况,当对象B的prototype为null将会报错(类似于空指针异常)。

看下面一段代码

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: