ES6 class 类

ES5 创建对象

  1. 在 ES5 中可以通过构造函数去实例化对象。

  2. 代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // 构造函数
    function Phone(brand,price){
    this.brand = brand;
    this.price = price;
    }

    // 添加方法
    Phone.prototype.call = function(){
    console.log('拨打电话');
    }

    // 实例化对象
    let Iphone = new Phone('iphone 13',5999);
    console.log(Iphone);

ES6 创建对象

  1. 通过 class 创建对象。

  2. 类中的构造方法的方法名必须是 constructor,构造方法会是 new 实例对象时调用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Phone {
    // 构造方法
    constructor(brand,price){
    this.brand = brand;
    this.price = price;
    };

    // 普通方法
    call(){
    console.log('拨打电话');
    }
    }

    let Huawei = new Phone('华为',3999);
    console.log(Huawei);

静态成员

  1. 静态成员属于类,不属于单个对象。

  2. 定义静态成员的关键字:static

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class Phone {
    static name = '手机';
    static call(){
    console.log('拨打电话');
    }
    }

    let Huawei = new Phone();
    console.log(Huawei.name);
    console.log(Phone.name);

类的继承

  1. 关键字:extends

  2. 继承父类后,父类中的所有非静态成员子类对象均可使用。

  3. 在子类中可以通过 super 调用父类的成员。

  4. 在子类的构造方法中使用 super() 完成继承属性的初始化。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    class People {
    constructor(name,age){
    this.name = name;
    this.age = age;
    }
    run(){
    console.log('跑步');
    }
    static play(){
    console.log('玩');
    }
    }

    class Student extends People {
    constructor(name,age,id){
    super(name,age);
    this.id = id;
    }
    speak(){
    super.run();
    console.log('我可以说话');
    }
    }

    let stu = new Student('张三',21,20210010);
    console.log(stu);
    stu.speak();

方法重写

  1. 父类方法不满足子类需求时,子类可重写父类方法。

  2. 子类中可以定义一个和父类相同名称的方法,记为重写。

  3. 方法重写后,子类实例对象调用该方法时会执行子类中的代码,不会执行父类里的。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    class People {
    constructor(name,age){
    this.name = name;
    this.age = age;
    }
    run(){
    console.log('跑步: 5km');
    }
    }

    class Student extends People {
    constructor(name,age,id){
    super(name,age);
    this.id = id;
    }
    run(){
    console.log('跑步: 10km');
    }
    }

    let stu = new Student('张三',21,20210010);
    stu.run();

get 和 set

  1. 在 class 中可以通过 get 拿到属性的值,通过 set 设置属性的值。

  2. get 和 set 是对对象的一种保护。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Test {
    get num(){
    console.log('num 被调用');
    return 10
    }
    set num(e){
    console.log('num 被重新赋值');
    }
    }
    let test = new Test();
    console.log(test.num);
    test.num = 10;