web前端 - 继承

64 阅读1分钟
  • 实现继承是 ECMAScript 唯一支持的继承方式
  • 这主要是通过原型链实现的。
  • 继承实际的方法。

构造函数、原型对象、实例的联系。

- 构造函数.prototype = 原型对象
- 原型对象.constructor = 构造函数
- 实例.__proto__ = 原型对象

如何判断实例和原型的关系?

function Person(){}
const p = new Person()

1. intanceof || isPrototypeOf

console.log(p instanceof Person) //返回true
console.log(p instanceof Object) //返回true

console.log(Person.prototype.isPrototypeOf(p)) // 返回true
console.log(Object.prototype.isPrototypeOf(p)) // 返回true

原型链问题

  1. 原型链包含引用值的时候。当构造函数的原型对象是另一个构造函数的实例的时候,实例的引用值的改变会影响到所有实例。
function Person(){
 this.colors = ['red','green']
}

function ChildPerson(){}
// 改变ChildPerson的原型
ChildPerson.prototype = new Person()
const p = new ChildPerson()
const p1 = new ChildPerson()
p.colors.push('black')  // 实例引用值的改变会影响所有实例
p1.colors               // ['red','green','black']
  1. 子类型在实例化时不能给父类型的构造函数传参

盗用构造函数

function Person(){
 this.colors = ['red','green']
}
function ChildPerson(){
  // 继承Person
  Person.apply(this)
}
const p = new ChildPerson()
const p1 = new ChildPerson()
p.colors.push('black')  // 这样就不会影响
p1.colors               // ['red','green']

问题

无法继承原型链上的方法

组合继承 *** 用到最多的继承方式

function Person(){
 this.colors = ['red','green']
}
function ChildPerson(){
  // 继承Person
  Person.apply(this)
}
// 重置原型对象
ChildPerson.prototype = new Person()

原型式继承

function Create(o) {
 function Person() {}
 Person.prototype = o;
 return new Person();
}

缺点和原型链模式一样,object.create方式的原理