I noted some open issues on "Classes with Trait Composition"

Mark S. Miller erights at google.com
Thu May 19 16:01:16 PDT 2011


On Thu, May 19, 2011 at 3:00 PM, Luke Hoban <lukeh at microsoft.com> wrote:

> >> 2) The conventional JS pattern is to place methods on the prototype, not
> the instance, and many felt that the main thing classes need to provide is a
> syntax to make this traditional semantics easier to express.
>
> >This is the big one.
>
> Class syntax with class parameters instead of explicit constructors can
> still be defined to produce methods on the prototype, right?
>
> Andreas' example:
>
>  class Point(x, y) {
>   public function abs() { return Math.sqrt(x*x, y*y) }
>  }
>

Hi Luke, given the above code, the semantics I should expect is that abs
lexically captures the x and y in scope. Notice that abs nowhere makes any
mention of "this", so I wouldn't expect it to be "this" sensitive. "this"
sensitivity is one of the trickiest hazards of JavaScript, but so far it is
only raised by functions that explicitly mention this.

Say have a point pt and wish to store its abs method in some data structure
of ours, for purpose of calling it later:

    var absFuncs = [];

    function storeAbsFrom(pt) {
      absFuncs.push(pt.abs);
    }

    function getTotalAbs1() {
      let result = 0;
      for (let i = 0, len = absFuncs.length; i < len; i++) {
        result += absFuncs[i]();
      }
      return result;
    }

    function getTotalAbs2() {
      return absFuncs.reduce(0, function(sum, abs) {
        return sum + abs();
      });
    }

If abs lexically captured x and y, both of the above getTotalAbs functions
would work. Instead, with the suggested semantics, getTotalAbs1() returns
NaN and getTotalAbs2() throws a TypeError.


>
> Can effectively desguar to:
>
>  function Point(x,y) {
>     this.x = x;
>    this.y = y;
>  }
>   Point.prototype.abs = function() { return Math.sqrt(this.x*this.x,
> this.y*this.y); }
>
> Or, with private names, to a variant with the captured x and y stored as
> private fields on the instance.  It's really just a syntax choice between
> explicit constructor functions and parameterized class definitions.  There
> are many benefits to the latter, and many modern OO languages seem to be
> using this style effectively.
>

Most other OO languages don't have the this-confusion hazards that
JavaScript suffers from.


>
> Luke
>
>


-- 
    Cheers,
    --MarkM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110519/200b28e5/attachment.html>


More information about the es-discuss mailing list