Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  隐瞒了意图╮
    2020-11-22 02:42

    Updated answer:

    In ECMAScript 6, you can create static functions using the static keyword:

    class Foo {
    
      static bar() {return 'I am static.'}
    
    }
    
    //`bar` is a property of the class
    Foo.bar() // returns 'I am static.'
    
    //`bar` is not a property of instances of the class
    var foo = new Foo()
    foo.bar() //-> throws TypeError
    

    ES6 classes don't introduce any new semantics for statics. You can do the same thing in ES5 like this:

    //constructor
    var Foo = function() {}
    
    Foo.bar = function() {
        return 'I am static.'
    }
    
    Foo.bar() // returns 'I am static.'
    
    var foo = new Foo()
    foo.bar() // throws TypeError
    

    You can assign to a property of Foo because in JavaScript functions are objects.

提交回复
热议问题