4.原型和原型链

2021-06-30  本文已影响0人  yaoyao妖妖
image.png image.png

原型链就是多个对象通过 proto 的方式连接了起来。为什么 obj 可以访问到 valueOf 函数,就是因为 obj 通过原型链找到了 valueOf 函数。

image.png

重点: 继承的本质其实是原型链的形成;

继承实现的效果是:

 Child.prototype.__proto__ = Parent.Prototype;(子类原型的 __proto__  指向父类原型)

// 然后我们知道的是 parent.__proto__ = Parent.Prototype;
// 所以只要 Child.prototype = parent;(子类的原型指向父类的实例即可,父类的实例是共享一个父类的原型对象的)

应用: 原型继承

  1. 组合继承
function Parent() {
  this.val = value;
}
Parent.prototype.getValue = function() {
   console.log(this.val);
}

function Child(val) {
  Parent.call(this, value);
}
Child.prototype = new Parent();
  1. 寄生组合继承 (对组合继承优化)
function Parent(value) {
  this.val = value;
}
Parent.prototype.getValue = function() {
  console.log(this.val);
}

function Child() {
  Parent.call(this,value)
}
// 创建一个对象,以 Parent.protptype 为原型,而且拥有constructor属性的;
Child.Prototype = Object.create(Parent.protptype,{
  constructor: {
   value: Child,
   enumerable: false,
   writeable: true,
   configurable: true
  }
})

核心: 将父类的原型赋值给了子类,并且将构造函数设置为子类

Class 继承

Class Parent {
  constructor(value){
      this.val = value;
  }
  getValue() {
     console.log(this.val);
  }
}

Class Child extends Parent {
 constructor(value) {
    super(value)
    this.val = value;
  }
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true

组合继承图:


f657770d9caa88ff0f2ddce6adf679f.png

寄生继承图:


d7179e0ad06ddce5c4b015297e15f01.png
Class 继承图:
0ec8b771ceb3c6eb4ad9f8d126607cd.png
上一篇 下一篇

猜你喜欢

热点阅读