目錄

JS 繼承(2): constructor 的執行順序

三個 class A, B, C,依序繼承,測試 constructor 的執行關係

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class A {
  constructor() {
    console.log('A has been instantiated', this)
  }
  static color = 'red'
  counter = 0
  onClick() {
    console.log('A onClick')
  }
}

class B extends A {
  // default: constructor(...args) { super(...args); }
  constructor() {
    super()
    this.test = this.test.bind(this)
    console.log('B has been instantiated, ', this)
  }
  test() {
    console.log('B test', this)
  }
}

class C extends B {
  constructor() {
    super()
    this.test = this.test.bind(this)
    console.log('C has been instantiated, ', this)
  }
  test() {
    super.test()  // 等同於B.test.call(this)
    console.log('C test', this)
  }
}

new C().test()

Output

/2019/09/js-extends-constructor/output.png
Console Output