Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  情话喂你
    2020-11-22 02:37

    You can create a static variable in JavaScript like this below. Here count is the static variable.

    var Person = function(name) {
      this.name = name;
      // first time Person.count is undefined, so it is initialized with 1
      // next time the function is called, the value of count is incremented by 1
      Person.count = Person.count ? Person.count + 1 : 1;
    }
    
    var p1 = new Person('User p1');
    console.log(p1.constructor.count);   // prints 1
    var p2 = new Person('User p2');
    console.log(p2.constructor.count);   // prints 2
    

    You can assign values to the static variable using either the Person function, or any of the instances:

    // set static variable using instance of Person
    p1.constructor.count = 10;         // this change is seen in all the instances of Person
    console.log(p2.constructor.count); // prints 10
    
    // set static variable using Person
    Person.count = 20;
    console.log(p1.constructor.count); // prints 20
    

提交回复
热议问题