class语法糖

183 阅读1分钟

如何吃这个class语法糖?

没糖吃的时候:构造函数和原型混合使用来模拟类(模拟面向对象)

ES6: class 语法糖出现 (关注注释,舒舒服服吃掉这个语法糖) ===> 其实还是原型链那一套

class Car {
  // 这里的属性在对象上,不会出现在prototype
    constructor(cColor, iDoors) {
        this.color = cColor; //颜色
        this.doors = iDoors; //车门数量
    }
  // 相当于 Car.prototype.showColor
    showColor() {
        console.log(`The color of the car is ${this.color}.`);
    }
    showDoors() {
        console.log(`The Car has ${this.doors} doors.`);
    }
}
// Test
let car = new Car('red', 4);
car.showColor();
car.showDoors();

类的表达式:棒棒糖,带根棍子的糖(还是那个class语法糖)

使用表达式,取别名

let Car = class {
    constructor(cColor, iDoors) {
        this.color = cColor; //颜色
        this.doors = iDoors; //车门数量
    }
    showColor() {
        console.log(`The color of the car is ${this.color}.`);
    }
    showDoors() {
        console.log(`The Car has ${this.doors} doors.`);
    }
}

// Test
let mycar = new Car('Yellow', 2);
mycar.showColor();
mycar.showDoors();

花式吃糖:应用 ,单例模式 + class语法糖

let mycar = new class {
    constructor(cColor, iDoors) {
        this.color = cColor; //颜色
        this.doors = iDoors; //车门数量
    }
    showColor() {
        console.log(`The color of the car is ${this.color}.`);
    }
    showDoors() {
        console.log(`The Car has ${this.doors} doors.`);
    }
}('Blue', 1);

// Test
mycar.showColor();
mycar.showDoors();

项目地址

  1. github.com/suckitfa/js…