Harmony:classes static and private

Mark S. Miller erights at google.com
Tue Jun 7 15:31:51 PDT 2011


On Tue, Jun 7, 2011 at 3:15 PM, Kam Kasravi <kamkasravi at yahoo.com> wrote:

>
> In the harmony:classes proposal the following example is provided:
>
> class Monster {
>  // "static" places the property on the constructor.
>  static allMonsters = [];
>
>  // "public" declares on the prototype.
>  public numAttacks = 0;
>
>  // "private" places it on the private record of the new instance.
>  private health;
> }
>
> According to the grammar it doesn't appear that static and private are
> allowed together. That is
>  static private allMonsters = [];
> would be an error. However I think this is a common use case, for example
> Monster may wish to
> implement a constructor based dependency injection pattern as:
>
> class Monster {
>  constructor(name, health) {
>    public name = name;
>    private health = health;
>    Monster.allMonsters.push(this);
>  }
>  static allMonsters = [];
> }
>
> class YourMammaMonster extends Monster {
>  constructor(name,posse) {
>    super(name, 10);
>    private posse = posse;
>  }
>  set health(value) {
>    private(this).health = value*0.5;
>  }
> }
>
> In this scenario, Monster would want strong encapsulation of allMonsters.
> Have the authors considered this use case? Are their alternative patterns to
> achieve a similar result?
>

Hi Kam, good example!

In the proposal as it stands, you can achieve this by lexical capture. The
following use of "module" is not essential, but it makes the lexical capture
pattern a bit more straightforward:

    module {
      allModules = [];
      export class Monster {
        constructor(name, health) {
          public name = name;
          private health = health;
          allMonsters.push(this);
        }
      }
    }

We have talked about adding some way to state class-private per-class
variable declarations without having to place them textually outside the
class. However, a problem with "static private" is that it suggests that
such things are properties. They're not. They're just lexically captured
variables.


-- 
    Cheers,
    --MarkM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110607/2fbe9c5b/attachment-0001.html>


More information about the es-discuss mailing list