ES6 class variable alternatives

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

提交回复
热议问题