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

后端 未结 5 2030
滥情空心
滥情空心 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:15

    There is a Stage 3 ECMAScript proposal called "Static Class Features" by Daniel Ehrenberg and Jeff Morrison that aims to solve this problem. Along with the Stage 3 "Class Fields" proposal, future code will look like this:

    class MyClass {
        static myStaticProp = 42;
        myProp = 42;
        myProp2 = this.myProp;
        myBoundFunc = () => { console.log(this.myProp); };
    
        constructor() {
            console.log(MyClass.myStaticProp); // Prints '42'
            console.log(this.myProp); // Prints '42'
            this.myBoundFunc(); // Prints '42'
        }
    }
    

    The above is equivalent to:

    class MyClass {
        constructor() {
            this.myProp = 42;
            this.myProp2 = this.myProp;
            this.myBoundFunc = () => { console.log(this.myProp); };
    
            console.log(MyClass.myStaticProp); // Prints '42'
            console.log(this.myProp); // Prints '42'
            this.myBoundFunc(); // Prints '42'
        }
    }
    MyClass.myStaticProp = 42;
    

    Babel supports transpiling class fields through @babel/plugin-proposal-class-properties (included in the stage-3 preset), so that you can use this feature even if your JavaScript runtime doesn't support it.


    Compared to @kangax's solution of declaring a getter, this solution can also be more performant, since here the property is accessed directly instead of through calling a function.

    If this proposal gets accepted, then it will be possible to write JavaScript code in a way that's more similar to traditional object-oriented languages like Java and C♯.


    Edit: A unified class fields proposal is now at stage 3; update to Babel v7.x packages.

    Edit (Feb 2020): The static class features have been split out into a different proposal. Thanks @GOTO0!

提交回复
热议问题