Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 02:33

    Summary:

    In ES6/ES 2015 the class keyword was introduced with an accompanied static keyword. Keep in mind that this is syntactic sugar over the prototypal inheritance model which javavscript embodies. The static keyword works in the following way for methods:

    class Dog {
    
      static bark () {console.log('woof');}
      // classes are function objects under the hood
      // bark method is located on the Dog function object
      
      makeSound () { console.log('bark'); }
      // makeSound is located on the Dog.prototype object
    
    }
    
    // to create static variables just create a property on the prototype of the class
    Dog.prototype.breed = 'Pitbull';
    // So to define a static property we don't need the `static` keyword.
    
    const fluffy = new Dog();
    const vicky = new Dog();
    console.log(fluffy.breed, vicky.breed);
    
    // changing the static variable changes it on all the objects
    Dog.prototype.breed = 'Terrier';
    console.log(fluffy.breed, vicky.breed);

提交回复
热议问题