How can I create static variables in Javascript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
In addition to the rest, there's currently a draft (stage-2 proposal) on ECMA Proposals that introduces
static
public fields in classes. (private fields were considered)Using the example from the proposal, the proposed
static
syntax will look like this:and be equivalent to the following which others have highlighted:
You can then access it via
CustomDate.epoch
.You can keep track of the new proposal in
proposal-static-class-features
.Currently, babel supports this feature with the transform class properties plugin which you can use. Additionally, though still in progress,
V8
is implementing it.There is no such thing as an static variable in Javascript. This language is prototype-based object orientated, so there are no classes, but prototypes from where objects "copy" themselves.
You may simulate them with global variables or with prototyping (adding a property to the prototype):
Updated answer:
In ECMAScript 6, you can create static functions using the
static
keyword:ES6 classes don't introduce any new semantics for statics. You can do the same thing in ES5 like this:
You can assign to a property of
Foo
because in JavaScript functions are objects.To condense all class concepts here, test this:
Well, another way to take a look to best practices in these things, is to just see how coffeescript translates these concepts.
Try this one:
If we define a property and override its getters and setters to use the Function Object property then in theory you can have an static variable in javascript
for example: