Skip to content

JS-ESNext-super #106

Open
Open
@yaofly2012

Description

@yaofly2012

super关键词

一、原来super不只是用在class里,任何对象都可以使用。

1.1 语法规则

var obj1 = {
     name: 'obj1',
     method1() {
        console.log('method 1');
        console.log(`name: ${this.name}`)
     }
}

var obj2 = {
    name: 'obj2',
    method2() {
        super.method1();
    }
}

Object.setPrototypeOf(obj2, obj1);

//method 1
// name: obj2
obj2.method2(); 
  1. super只是子对象访问原型属性的一种方式,并不是原型;
  2. 对象通过super调用父对象方法的this是子对象(这个原则);
//method 1
// name: obj2
obj2.method2(); 
//method 1
// name: obj1
obj2.__proto__.method1();
  1. 子对象通过super只能访问原型属性,但不能修改原型属性(这也是原则);
var obj2 = {
    name: 'obj2',
    method2() {
        super.name = 'change' // 赋值失败
        console.log(super.name) // “obj1”
        super.method1();
    }
}
  1. super必须以对象访问的性质存在,其他都是语法错误;
var obj2 = {
    name: 'obj2',
    method2() {
       typeof super; // SyntaxError: 'super' keyword unexpected here
        super.method1();
    }
}

总结:对象中引入super的目的是为了方便调用被子对象覆盖的父对象的方法,其他任何对父对象的操作都无法(也不准许)通过super进行。

1.2 super的 polyfill

直接看Babel如何做的

Issues

  1. Babel中获取_getPrototypeOf判断唯一依赖Object.setPrototypeOf ?
function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf
    ? Object.getPrototypeOf
    : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };
  return _getPrototypeOf(o);
}

参考

  1. MDN super

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions