JavaScript ES6 super Keyword

在 ES6 中新增的 super 關鍵字 (keyword),在物件的方法 (method) 中使用時,super 會指向父類別 (的 prototype),方便你可以存取父類別中的。

例子:

var parent = {
  foo() {
    console.log('Hello from the Parent');
  },
  a: 'a of parent',
};

var child = {
  foo() {
    console.log('Hello from the child');
    super.foo();

    console.log(this.a);
    console.log(super.a);
  },
  a: 'a of child',
};

Object.setPrototypeOf(child, parent);

child.foo();

上面依序會輸出:

Hello from the child Hello from the Parent a of child a of parent

需要特別注意的是 super 只能用在 ES6 新的 method 語法 中,用在傳統的函數 function 語法中會引發錯誤:

var child = {
    foo: function() {
        super.foo();
    }
}

// Uncaught SyntaxError: 'super' keyword unexpected here