浅谈ES6中super关键字

作用:

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

语法:

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

详解:

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

1 类(prototype相关)

a 用在子类constructor函数中

 1 class Person {
 2   constructor (name) {
 3     this.name = name;
 4   }
 5 }
 6 class Student extends Person {
 7   constructor (name, age) {
 8     super(); // 用在构造函数中,必须在使用this之前调用
 9     this.age = age;
10   }
11 }

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

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

b 调用父类的静态函数

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

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

 1 var obj1 = {
 2   method1() {
 3     console.log("method 1");
 4   }
 5 }
 6 
 7 var obj2 = {
 8   method2() {
 9    super.method1();
10   }
11 }
12 // 必须利用setPrototypeOf将第二个对象的原型设为第一个对象
13 Object.setPrototypeOf(obj2, obj1);
14 obj2.method2(); // logs "method 1"
posted @ 2016-10-25 17:17  5Mi17  阅读(20643)  评论(0编辑  收藏  举报