How do I make a “public static field” in an ES6 class?

后端 未结 5 2040
滥情空心
滥情空心 2020-11-27 14:13

I\'m making a Javascript class and I\'d like to have a public static field like in Java. This is the relevant code:

export default class Agent {
    CIRCLE:          


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 15:01

    To get full advantage of static variable I followed this approach. To be more specific, we can use it to use private variable or having only public getter, or having both getter or setter. In the last case it's same as one of the solution posted above.

    var Url = (() => {
        let _staticMember = [];
        return class {
            static getQueries(hash = document.location.hash) {
                return hash;
            }
    
            static get staticMember(){
                return _staticMember;
            }
        };
    })();
    
    Usages:
    console.log(Url.staticMember); // [];
    Url.staticMember.push('it works');
    console.log(Url.staticMember); // ['it works'];
    

    I could create another class extending Url and it worked.

    I used babel to convert my ES6 code to ES5

提交回复
热议问题