对于原型链的理解:
1.js实现封装继承的方法。
2.关键点:构造函数生成的实例对象的__proto__指向构造函数的protorype属性。利用这个特点,js实现了构造函数的数据与方法共享给实例对象。
Instanceof 的原理也是原型链。
ES6的 class只是语法糖,本质还是原型链的实现方式。
原型链的图:
js实现 面向对象编程方式的demo:
function Parent() { this.name = 'ssx' } var Child = function (age) { Parent.call(this) this.age = age } Child.prototype = Object.create(Parent.prototype) Child.prototype.constructor = Child Child.prototype.setAge = function(age){ this.age = age } var s = new Child(18) console.log("名字",s.name) console.log("年龄",s.age) s.setAge(20) console.log("年龄",s.age)理解原型链还要理解new 关键字做了什么,demo:
function testF(name){ this.name = name } var testObj = new testF('ssx') console.log("testObj------",testObj) function newF(fun,arg) { let o = Object.create(fun.prototype) let temp = fun.call(o,arg) if(typeof temp === 'Object'){ return temp }else { return o } } var testObj2 = newF(testF,'ssx') console.log("testObj2------",testObj2)