ES6 class variable alternatives

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

    In your example:

    class MyClass {
        const MY_CONST = 'string';
        constructor(){
            this.MY_CONST;
        }
    }
    

    Because of MY_CONST is primitive https://developer.mozilla.org/en-US/docs/Glossary/Primitive we can just do:

    class MyClass {
        static get MY_CONST() {
            return 'string';
        }
        get MY_CONST() {
            return this.constructor.MY_CONST;
        }
        constructor() {
            alert(this.MY_CONST === this.constructor.MY_CONST);
        }
    }
    alert(MyClass.MY_CONST);
    new MyClass
    
    // alert: string ; true
    

    But if MY_CONST is reference type like static get MY_CONST() {return ['string'];} alert output is string, false. In such case delete operator can do the trick:

    class MyClass {
        static get MY_CONST() {
            delete MyClass.MY_CONST;
            return MyClass.MY_CONST = 'string';
        }
        get MY_CONST() {
            return this.constructor.MY_CONST;
        }
        constructor() {
            alert(this.MY_CONST === this.constructor.MY_CONST);
        }
    }
    alert(MyClass.MY_CONST);
    new MyClass
    
    // alert: string ; true
    

    And finally for class variable not const:

    class MyClass {
        static get MY_CONST() {
            delete MyClass.MY_CONST;
            return MyClass.MY_CONST = 'string';
        }
        static set U_YIN_YANG(value) {
          delete MyClass.MY_CONST;
          MyClass.MY_CONST = value;
        }
        get MY_CONST() {
            return this.constructor.MY_CONST;
        }
        set MY_CONST(value) {
            this.constructor.MY_CONST = value;
        }
        constructor() {
            alert(this.MY_CONST === this.constructor.MY_CONST);
        }
    }
    alert(MyClass.MY_CONST);
    new MyClass
    // alert: string, true
    MyClass.MY_CONST = ['string, 42']
    alert(MyClass.MY_CONST);
    new MyClass
    // alert: string, 42 ; true
    

提交回复
热议问题