继承

2021-12-06  本文已影响0人  三省吾身_9862
  1. 原型链继承,缺点:引用类型属性list改了,会影响其他实例
function Super() {
  this.list = [1,2]
}

Super.prototype.sayAge = function () {
  console.log(this.age)
}

function Sub(age) {
  this.age = age;
}

Sub.prototype = new Super()

var s1 = new Sub(30) 
s1.list.push(3)
var s2 = new Sub(30) 
s2.list // [1,2,3]
  1. 借用构造函数,函数被call来使用,无法继承函数的原型
function Super() {
  this.list = [1,2]
}

Super.prototype.sayAge = function () {
  console.log(this.age)
}

function Sub(age) {
  this.age = age;
  Super.call(this)
} 

var s1 = new Sub(30)
s1.sayAge // undefined
  1. 组合继承;结合上面的两个继承,互补利弊;唯一不足,实例通过Super.call有的属性,原型上 new Super()也有,重复了
function Super(name) {
  this.name = name
  this.list = [1,2]
}

Super.prototype.sayAge = function () {
  console.log(this.age)
}

function Sub(name, age) {
  Super.call(this, name)
  this.age = age;
} 

Sub.prototype = new Super()

var s1 = new Sub('kp', 30)
s1原型上,属性重复
  1. 寄生组合式继承,Sub.prototype是一个空对象new F()【代替new Super()】这个空对象的构造函数原型是Super.prototype;解决上面问题: 原型上 new Super()也有,重复了 的问题
function object(o){ 
  function F(){} 
  F.prototype = o; 
  return new F(); 
} 

function Super(name) {
  this.name = name
  this.list = [1,2]
}

Super.prototype.sayAge = function () {
  console.log(this.age)
}

function Sub(name, age) {
  Super.call(this, name)
  this.age = age;
} 

Sub.prototype = object(Super.prototype)
// Sub.prototype = Object.create(Super.prototype) // 上一行代码,可以用Object.create,代替object这个自定义方法
Sub.prototype.constructor = Sub
var s1 = new Sub('kp', 30)
s1
s1原型上,没有重复属性
  1. class 继承,采用的就是 【4. 寄生组合式继承】
class Super{
  constructor(name) {
    this.name = name
  }

  sayAge() {
    console.log(this.age)
  }
}

class Sub extends Super{
  constructor(name, age) {
    super(name)
    this.age = age
  }
}

var s1 = new Sub('kp', 30)
s1 - class继承
上一篇 下一篇

猜你喜欢

热点阅读