How can I create static variables in Javascript?
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.