理解Javascript_07_理解instanceof实现原理

来源:互联网 发布:关于php的知识 编辑:程序博客网 时间:2024/04/30 01:39

理解Javascript_07_理解instanceof实现原理


在《Javascript类型检测》一文中讲到了用instanceof来用做检测类型,让我们来回顾一下:


 那么instanceof的这种行为到底是如何实现的呢,现在让我们揭开instanceof背后的迷雾。

 

instanceof原理

照惯例,我们先来看一段代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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

让我们画一张内存图来分析一下:


内存图比较复杂,解释一下:

程序本身是一个动态的概念,随着程序的执行,Dog.prototype会不断的改变。但是为了方便,我只画了一张图来表达这三次prototype引用的改变。在堆中,右边是函数对象的内存表示,中间的是函数对象的prototype属性的指向,左边的是函数对象创建的对象实例。其中函数对象指向prototype属性的指针上写了dog1,dog2,dog3分别对应Dog.prototype的三次引用改变。它们和栈中的dog1,dog2,dog3也有对应的关系。(注:关于函数对象将在后续博文中讲解)

来有一点要注意,就是dog3中函数对象的prototype属性为null,则函数对象实例dog3的内部[[prototype]]属性将指向Object.prototype,这一点在《理解Javascript_06_理解对象的创建过程》已经讲解过了。

 

结论

根据代码运行结果和内存结构,推导出结论:

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

 

这里推荐一篇文章,来自于岁月如歌,也是关于instanceof原理的,角度不同,但有异曲同工之妙。

1

http://lifesinger.org/blog/2009/09/instanceof-mechanism/


0 0
原创粉丝点击