ES6 class variable alternatives

前端 未结 15 2383
长发绾君心
长发绾君心 2020-11-22 06:04

Currently in ES5 many of us are using the following pattern in frameworks to create classes and class variables, which is comfy:



        
15条回答
  •  眼角桃花
    2020-11-22 06:28

    ES7 class member syntax:

    ES7 has a solution for 'junking' your constructor function. Here is an example:

    class Car {
      
      wheels = 4;
      weight = 100;
    
    }
    
    const car = new Car();
    console.log(car.wheels, car.weight);

    The above example would look the following in ES6:

    class Car {
    
      constructor() {
        this.wheels = 4;
        this.weight = 100;
      }
    
    }
    
    const car = new Car();
    console.log(car.wheels, car.weight);

    Be aware when using this that this syntax might not be supported by all browsers and might have to be transpiled an earlier version of JS.

    Bonus: an object factory:

    function generateCar(wheels, weight) {
    
      class Car {
    
        constructor() {}
    
        wheels = wheels;
        weight = weight;
    
      }
    
      return new Car();
    
    }
    
    
    const car1 = generateCar(4, 50);
    const car2 = generateCar(6, 100);
    
    console.log(car1.wheels, car1.weight);
    console.log(car2.wheels, car2.weight);

提交回复
热议问题