Look Ma, no "this" (was: ECMAScript Harmony)

Peter Michaux petermichaux at gmail.com
Mon Aug 25 00:34:34 PDT 2008


On Sun, Aug 24, 2008 at 9:44 PM, Kris Zyp <kris at sitepen.com> wrote:

> Desugared from:

> class Point {
>   private var x = Math.random();
>   function getX(){
>       return this.x;
>   }
>   ...
> }

Is there any need for the "this."? Some languages allow "this.x" to
get out from under the shadow of a local "x" inside "getX". I don't
think it is necessary to be able to escape such shadowing and actually
increases confusion. If a method is many lines long then the reader
may forget that "x" is local and not the instance variable. I would
just call the local variable "locx" or "xx" or something different. I
would actually rather see the "this." shadow escaping be disallowed.

In the above code snip it seems that properties will be public unless
listed as private. In the security world, whitelisting is considered a
best practice as blacklisting can accidentally leave things out in
public that should not be. Whitelisting inside a class would be
explicitly labeling things as public.

Going with a default-private, whitelisting system we would have...

class Point {
   var x = Math.random();
   public function getX(){
       return this.x;
   }
   ...
}

This is problematic as "var" is being used to define a variable with
scope inside the class's braces. I don't know if that will fly well
and is analogous to the issue discussed lately where "return" inside a
"let" statement's block was considered confusing if a "let" desugars
to a function. The reasoning being a programmer sees "return" and
immediately looks up to the nearest "function" keyword. "var" inside
"let" statement is the same issue. Anyway, programmers are currently
used to seeing "var" and looking up the nearest "function" keyword.
Whether or not programmers can learn to change is an argument I was
not successful convincing Brendan about for the "let" situation though
he also wants different semantics anyway (and I understand his case.)

I don't know if it makes sense that "let" could be used instead of
"var" as "let" declarations scope are the closest surrounding braces?
Is it even that simple?

Perhaps just use "private" or "public" instead of "var"?

What about the following two options:

class Point {
   private x = Math.random();
   public function getX(){
       return x;
   };
}

var Point = class {
   private x = Math.random();
   public getX = function(){
       return x;
   };
};

If only one option could be included I'd *much* prefer the final
option as "var" could be changed to "let" so I control the class's
scope better.

In either of the last two cases, I imagine that the "Point" variable
is pointing to a first-class class objects (which desugars to a
constructor function) that I could pass around, yes?

Peter


More information about the Es-discuss mailing list