js原型链图
首先,介绍一个详细博客:https://www.jianshu.com/p/a4e1e7b6f4f8;大家可以看看,写的很好;总结下自己的所得和不解。
以下几条要记住,
1. js中一切皆对象,分为函数对象和普通对象两类。
2. 函数对象的构造函数都是Function,普通对象的构造函数都是Object。
3. 实例的__proto__和构造函数的prototype永远相等。(重写原型时constructor就会变)。
下面是本人画的一张图
Function有点特别。有个自定义函数的相关链接没画上,下面把他写上
function Person() {}; var p = new Person(); console.log(Person.prototype); console.log(Person.__proto__); console.log(Person.constructor); console.log(p.__proto__); console.log(p.constructor); console.log(Person.__proto__ === Function.prototype);//true console.log(Person.prototype.__proto__ === Object.prototype);//true
最后一句,Person.prototype是一个普通对象,普通对象的构造函数是Object。
下面这两段代码还是不太理解,先记住
function Person() {} // 重写原型 Person.prototype = { getName: function() {} } var p = new Person() console.log(p.__proto__ === Person.prototype) // true console.log(p.__proto__ === p.constructor.prototype) // false
var animal = function(){}; var dog = function(){}; animal.price = 2000; dog.prototype = animal; var tidy = new dog(); console.log(dog.price) //undefined console.log(tidy.price) // 2000 console.log(animal.price) // 2000自己敲代码,把Function,Objective,自定义函数,实例化等等的prototype,__proto__,constructor都输出看看,然后自己在纸上关系图,基本就能理解大多数了。原型链的作用就是继承方法。实例对象会继承构造函数的原型对象上的所有方法。