ES6 class variable alternatives

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

    [Long thread, not sure if its already listed as an option...].
    A simple alternative for contsants only, would be defining the const outside of class. This will be accessible only from the module itself, unless accompanied with a getter.
    This way prototype isn't littered and you get the const.

    // will be accessible only from the module itself
    const MY_CONST = 'string'; 
    class MyClass {
    
        // optional, if external access is desired
        static get MY_CONST(){return MY_CONST;}
    
        // access example
        static someMethod(){
            console.log(MY_CONST);
        }
    }
    

提交回复
热议问题