ES6 — class类

1、概述

在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类

class 的本质是 function

它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。

2、基础用法

  1、类定义

// 匿名类
let Example = class {
    constructor(a) {
        this.a = a;
    }
}
// 命名类
let Example = class Example {
    constructor(a) {
        this.a = a;
    }
}

  2、类声明

class Example {
    constructor(a) {
        this.a = a;
    }
}

  

注意:

类定义不会被提升,这意味着,必须在访问前对类进行定义,否则就会报错。

类中方法不需要 function 关键字。

方法间不能加分号。

3、类的主体

  1、属性:

  ES6 中,prototype 仍旧存在,虽然可以直接自类中定义方法,但是其实方法还是定义在 prototype 上的。 覆盖方法 / 初始化时添加方法。

Example.prototype={
    //methods
}

  2、静态属性:

  class 本身的属性,即直接定义在类内部的属性( Class.propname ),不需要实例化。 ES6 中规定,Class 内部只有静态方法,没有静态属性。

  3、公共属性:

class Example{}
Example.prototype.a = 2;

  4、实例属性:定义在实例对象( this )上的属性。

  5、name属性:就是class的名称,返回跟在 class 后的类名(存在时)。

4、方法:

  1、constructor方法(构造方法):创建类的实例化对象时被调用。

class Example{
    constructor(){
      console.log('我是constructor');
    }
}
new Example(); // 我是constructor

  2、静态方法:函数前缀为static。

  3、原型方法:无前缀的函数。

  4、实例方法:在constructor方法中调用的方法。

4、类的实例化

  1、class 的实例化必须通过 new 关键字。

  2、decrator: decorator 是一个函数,用来修改类的行为,在代码编译时产生作用。

5、封装与继承 getter和setter

class Example{
    constructor(a, b) {
        this.a = a; // 实例化时调用 set 方法
        this.b = b;
    }
    get a(){
        console.log('getter');
        return this.a;
    }
    set a(a){
        console.log('setter');
        this.a = a; // 自身递归调用
    }
}
let exam = new Example(1,2); // 不断输出 setter ,最终导致 RangeError
class Example1{
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    get a(){
        console.log('getter');
        return this._a;
    }
    set a(a){
        console.log('setter');
        this._a = a;
    }
}
let exam1 = new Example1(1,2); // 只输出 setter , 不会调用 getter 方法
console.log(exam1._a); // 1, 可以直接访问

  extends 继承:class Child extends Father { ... }

    子类 constructor 方法中必须有 super ,且必须出现在 this 之前。

    调用父类构造函数,只能出现在子类的构造函数。

    调用父类方法, super 作为对象,在普通方法中,指向父类的原型对象,在静态方法中,指向父类

class father{
    a = 10;
}

class child extends father{
    constructor () {
        super()
        console.log(this.a);
    }
}

let child1 = new child();
// 10

  

posted @ 2021-09-26 21:54  小绵杨Lamb  阅读(123)  评论(0)    收藏  举报