zoukankan      html  css  js  c++  java
  • 浅谈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"
  • 相关阅读:
    win7台式机上使用airpods
    通达信自定义版面设置
    pthread_cond_wait函数实现
    为什么卸载手机微软必应浏览器
    看电子书的好处
    Web前端学习方法
    用Bing搜索单词的时候按下Ctrl键不放可以持续发音
    怎么制作档案盒标签
    三个按钮指向一个Click事件的错误
    What is .NET
  • 原文地址:https://www.cnblogs.com/liutie1030/p/5997446.html
Copyright © 2011-2022 走看看