zoukankan      html  css  js  c++  java
  • ES6中的类

    ES6中的类

    1. class

      class Fo {
          constructor(a,b) {
              this.x = a;
              this.y = b;
          }
          
          gimmeXY() {
              return this.x * this.y;
          }
      }
      

      等价于如下代码

      function Fo(a, b) {
          this.x = a;
          this.y = b;
      }
      
      Fo.prototype.gimmeXY = () => this.x * this.y;
      

      以上两种方式的区别

      1. function Fo有变量提升,class Fo并不会提升(所以实例化一个class之前要先声明)
      2. class Fo并不会创建一个window属性

    2.extends和super

    class Bar extends Fo {
        constructor(a, b, c) {
            super(a, b, c);
            this.z = c;
        }
        
        gimmeXYZ() {
            return super.gimmeXY() * this.z;
        }
    }
    
    class ParentA {
        constructor() {
            this.id = "a";
        }
        foo() {
            console.log("ParentA:", this.id);
        }
    }
    
    class ChildA extends ParentA {
        foo() {
            super.foo();
            console.log("ChildA:", this.id);
        }
    }
    
    var a = new ChildA();
    a.foo(); // Parent: a
    		 // ChildA: a
    
    class ParentB {
        constructor() {
            this.id = "b";
        }
        foo() {
            console.log("ParentB:", this.id);
        }
    }
    
    class ChildB extends ParentB {
        foo() {
            super.foo();
            console.log("ChildB:", this.id);
        }
    }
    
    var b = new ChildB();
    b.foo();	// ParentB: b
    			// ChildB: b
    
    b.foo.call(a);	// ParentB: a
    				// ChildB: a
    // this.id被动态绑定,super.foo()并没有被动态绑定
    

    3.子类构造器

    • 类和子类的构造器并不是必须的;省略的话会自动提供一个默认构造器

    • 默认构造器可以认为是这样的

      constructor(...args) {
          super(...args);
      }
      
      1. 子类构造器中调用super(...)之后才能访问this(机制,可以理解为对实例中this进行创建/实例化的是父构造器
      class Foo {
          constructor() { this.a = 1; }
      }
      class Bar extends Foo {
          constrcutor() {
              this.b = 2;	//不允许在super()之前使用this
              super();	// Uncaught SyntaxError: 'super' keyword unexpected here
          }
      }
      
  • 相关阅读:
    P12 向量组03--极大线性无关组
    超导体
    Matlab中disp、fprintf和sprintf有什么区别?
    点击word页面自动弹出信息检索很烦人
    Postman 官方中文版 v7.25.3
    无法为更新定位行。一些值可能已在最后一次读取后已更改解决办法
    Everything文件查找工具
    Delphi的DataSource事件
    Delphi中inherited问题
    delphi窗体继承
  • 原文地址:https://www.cnblogs.com/wydumn/p/11788040.html
Copyright © 2011-2022 走看看