minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

31 - 【经典面试】js继承 #31

Open FE92star opened 3 years ago

FE92star commented 3 years ago

Javascript常用的继承方式有哪些?各自的应用场景有哪些?

FE92star commented 3 years ago
  1. 原型链继承——引用类型值的原型属性会被所有的实例所共享;
    function SuperType() {
    this.colors = ['red', 'blue', 'green']
    }
    function SubType() {}
    // 原型继承
    SubType.prototype = new SuperTYpe()
    // 创建实例
    var instance1 = new SubType()
    instance1.colors.push('black')
    alert(instance1.colors) // ['red', 'blue', 'green', 'black']
    var instances2 = new SubType()
    alert(instance2.colors) // ['red', 'blue', 'green', 'black']
FE92star commented 3 years ago
  1. 借用构造函数
    
    function SuperType() {
    this.colors = ['red', 'blue', 'green']
    }
    function SubType() {
    // 继承了SuperType
    SuperType.call(this)
    }
    // 创建实例
    var instance1 = new SubType()
    instance1.colors.push('black')
    alert(instance1.colors) // ['red', 'blue', 'green', 'black']

var instances2 = new SubType() alert(instance2.colors) // ['red', 'blue', 'green']


优势——继承的时候可以传递参数
劣势——方法都是在构造函数中定义,无法复用
Guyidingsanyu commented 3 years ago

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