zoukankan      html  css  js  c++  java
  • ES6中构造函数内super关键字的使用

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

    super.propsuper[expr]表达式在类和对象字面量任何方法定义中都是有效的。

    语法

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

    描述

    在构造函数中使用时,super关键字将单独出现,并且必须在使用this关键字之前使用。super关键字也可以用来调用父对象上的函数。

    示例

    在类中使用super

    class Polygon {
      constructor(height, width) {
        this.name = 'Polygon';
        this.height = height;
        this.width = width;
      }
      sayName() {
        console.log('Hi, I am a ', this.name + '.');
      }
    }
    
    class Square extends Polygon {
      constructor(length) {
        this.height; 
        // ReferenceError,super 需要先被调用!
        
    /*
       这里,它调用父类的构造函数的 length, 
       作为Polygon 的 width和 height.
    */ 
        super(length, length);
        
    /*
        注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()。
        忽略这, 这将导致引用错误。
    */
        this.name = 'Square';
      }
    
      get area() {
        return this.height * this.width;
      }
    
      set area(value) {
        this.area = value;
      } 
    }
    

      

    调用父类上的静态方法

    你也可以用 super 调用父类的静态方法。

    class Human {
      constructor() {}
      static ping() {
        return 'ping';
      }
    }
     
    class Computer extends Human {
      constructor() {}
      static pingpong() {
        return super.ping() + ' pong';
      }
    }
    Computer.pingpong(); // 'ping pong'
    

      

  • 相关阅读:
    NAMESPACE
    所谓has a 和 is a
    C++ 的多重继承
    c# 与 c++ 编译
    初始化的顺序:和定义的顺序以及初始化函数都有关系。都要先定义的在前,后定义的在后。甚至连类的顺序都必须这样。
    关于转换
    隐藏
    第四章第四个例题(LRJ)
    初来扎到啊(觉得有些神圣尼)
    理解JS的执行环境
  • 原文地址:https://www.cnblogs.com/laneyfu/p/12082641.html
Copyright © 2011-2022 走看看