static/class properties

Rick Waldron waldron.rick at gmail.com
Thu Sep 19 06:30:39 PDT 2013


On Thu, Sep 19, 2013 at 4:16 AM, Dmitry Soshnikov <
dmitry.soshnikov at gmail.com> wrote:

> Hi,
>
> Out of curiosity: we have static methods, but seems there is no yet
> ability to define a class/static property/constant.
>
> class A {
>   const VALUE = 10;
> }
>
> or (probably better to be consistent with static methods):
>
> class A {
>   static VALUE = 10;
> }
>
>
There are a few reasons, the first being that there was no "static" prefix
when maximally minimal classes were accepted, but of course the class
feature grew a little (which is a good thing). "static", with regard to
methods, is straight forward, whereas data properties create a potential
ambiguity:

class A {
  const VALUE = 10;
}

A decision would have to be made for "const VALUE = 10" here: does it mean
mean `A.VALUE` and not `var a = new A(); a.VALUE;`? If it means the latter,
then there are implications that will change a possible future that
includes "private x = 1" in the same class-body position.

I spoke with Allen off-line and he reminded me that a static "const-like"
could be created like this:

class A {
  static get VALUE() { return "some constant value"; }
}

A.VALUE;

(I quoted const-like, because this is still configurable)




> Was it a special reason or was it just forgotten? (One could define a var
> in the static scope, but seems it's useful to have the feature inline in
> the class bodies).
>
> P.S.: in addition -- why not to reuse `static` for also simple functions?
>
> function getHeavyValue() {
>   static heavyValue;
>   if (!heavyValue) {
>     // heavy calc
>   }
>   return heavyValue;
> }
>
>
This is a no-go because "static" is only reserved in strict mode, which
means

function foo() {
  static = 1;
}

(awful, yes—but legal)


Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130919/f6684b33/attachment.html>


More information about the es-discuss mailing list