js的原型和原型链理解

以以下代码为例:

let arr = [1, 3, 2, 0]
arr.reverse()
arr.toString()

我们使用console.dir(arr)命令

发现arr._proto_属性上有reverse()和toString()方法了

用console.dir(arr)发现,arr不仅有我们定义的四个值,其proto属性上还有constructor和reverse()和toString()方法,我们并未定义它是从何而来呢?

这跟_proto_有关系,当我们读取reverse()方法时,js引擎会做以下事情:

1.先从自身属性找,没有进入下一步

2.从arr._proto_对象上找,看有没有reverse()属性。发现arr._proto_对象上有reverse()属性,其实arr.reverse()实际上就是arr._proto_.reverse()

3.如果arr._proto_对象上找不到,就依次从arr._proto_._proto_对象上找,arr._proto_._proto_._proto_,arr._proto_._proto_._proto_,一直到找到reverse()属性或者_proto_属性为null为止。

上面的过程就是读属性的搜索过程,这个围绕_proto_搜索的过程,即称之为原型链。

流程图

参考资料

https://zhuanlan.zhihu.com/p/23090041

猜你喜欢

转载自www.cnblogs.com/mernva/p/12921248.html