Static variables in JavaScript

后端 未结 30 2589
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  野的像风
    2020-11-22 02:28

    About the class introduced by ECMAScript 2015. The other answers are not totally clear.

    Here is an example showing how to create a static var staticVar with the ClassName.var synthax:

    class MyClass {
        constructor(val) {
            this.instanceVar = val;
            MyClass.staticVar = 10;
        }
    }
    
    var class1 = new MyClass(1);
    console.log(class1.instanceVar);      // 1
    console.log(class1.constructor.staticVar); // 10
    
    // New instance of MyClass with another value
    var class2 = new MyClass(3);
    console.log(class1.instanceVar);      // 1
    console.log(class2.instanceVar);      // 3
    

    To access the static variable we use the .constructor property that returns a reference to the object constructor function that created the class. We can call it on the two created instances:

    MyClass.staticVar = 11;
    console.log(class1.constructor.staticVar); // 11
    console.log(class2.constructor.staticVar); // 11 <-- yes it's static! :)
    
    MyClass.staticVar = 12;
    console.log(class1.constructor.staticVar); // 12
    console.log(class2.constructor.staticVar); // 12
    

提交回复
热议问题