浅谈ES6中super关键字

作用:

1

super 关键字用于访问父对象上的函数。

语法:

1

2

super([arguments]); // 访问父对象上的构造函数

super.functionOnParent([arguments]); // 访问对象上的方法

详解:

super可以用在类的继承中,或者对象字面量中,super指代了整个prototype或者__proto__指向的对象

1 类(prototype相关)

a 用在子类constructor函数中

 

class Person {
  constructor (name) {
    this.name = name;
  }
}
class Student extends Person {
  constructor (name, age) {
    super(); // 用在构造函数中,必须在使用this之前调用
    this.age = age;
  }
}

 

super()调用会生成一个空对象,作为context来调用父类的constructor,返回this对象,作为子类constructor的context继续调用构造函数。

context:执行上下文 constructor:构造函数

b 调用父类的静态函数

 

class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong';
  } // 只有在子类的静态函数中才能调用父类的静态函数(babel环境测试,按理说,在实例函数中应该也可以调用,不过实际测试环境中报错)
}
Computer.pingpong(); // 'ping pong'

 

 

2 对象的字面量(__proto__项目)

var obj1 = {
  method1() {
    console.log("method 1");
  }
}

var obj2 = {
  method2() {
   super.method1();
  }
}
// 必须利用setPrototypeOf将第二个对象的原型设为第一个对象
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"

 

 

转载地址:https://www.cnblogs.com/liutie1030/p/5997446.html

你可能感兴趣的:(前端,浅谈ES6中super关键字)