ES6 class variable alternatives

前端 未结 15 2127
长发绾君心
长发绾君心 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:26

    You can mimic es6 classes behaviour... and use your class variables :)

    Look mum... no classes!

    // Helper
    const $constructor = Symbol();
    const $extends = (parent, child) =>
      Object.assign(Object.create(parent), child);
    const $new = (object, ...args) => {
      let instance = Object.create(object);
      instance[$constructor].call(instance, ...args);
      return instance;
    }
    const $super = (parent, context, ...args) => {
      parent[$constructor].call(context, ...args)
    }
    // class
    var Foo = {
      classVariable: true,
    
      // constructor
      [$constructor](who){
        this.me = who;
        this.species = 'fufel';
      },
    
      // methods
      identify(){
        return 'I am ' + this.me;
      }
    }
    
    // class extends Foo
    var Bar = $extends(Foo, {
    
      // constructor
      [$constructor](who){
        $super(Foo, this, who);
        this.subtype = 'barashek';
      },
    
      // methods
      speak(){
        console.log('Hello, ' + this.identify());
      },
      bark(num){
        console.log('Woof');
      }
    });
    
    var a1 = $new(Foo, 'a1');
    var b1 = $new(Bar, 'b1');
    console.log(a1, b1);
    console.log('b1.classVariable', b1.classVariable);
    

    I put it on GitHub

    0 讨论(0)
  • 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);

    0 讨论(0)
  • 2020-11-22 06:31

    Well, you can declare variables inside the Constructor.

    class Foo {
        constructor() {
            var name = "foo"
            this.method = function() {
                return name
            }
        }
    }
    
    var foo = new Foo()
    
    foo.method()
    
    0 讨论(0)
提交回复
热议问题