`this`: methods versus functions

Andreas Rossberg rossberg at google.com
Thu Nov 10 07:19:01 PST 2011


On 10 November 2011 15:58, Axel Rauschmayer <axel at rauschma.de> wrote:
> I wonder if it made a difference if `this`was always stored in an
>
> environment (instead of an execution context). Then block lambdas could find
>
> them via the scope chain.
>
> If I understand you correctly, then yes, this is definitely possible
> in principle, and in fact corresponds to the standard model of objects
> as straightforward records-of-closures (closing over `this'). But you
> could not use prototypes directly anymore, because you would need to
> close their methods over `this' as well when you construct an object.
> IOW, this would require a more class-style approach to inheritance.
>
> I don’t understand. Can you give an example? I thought that simply turning
> `this` into a parameter (under the hood, like a hidden first parameter that
> all functions have) would not change anything:

No, that's how it works right now. The alternative is to lexically
close all methods over self at construction time:

  function Point(x, y) {
    var self = this
    self.x = x
    self.y = y
    self.move = function(dx, dy) { self.x += dx; self.dy += dy }
  }

  function ColorPoint(x, y, color) {
    var self = this
    Point.call(self, x, y)
    self.color = color
    self.recolor = function(c) { self.color = c }
  }

As said, this doesn't play well with prototype inheritance. You have
to put all methods that refer to self on the object itself. But "inner
constructors" are straighforward and safe.

/Andreas


More information about the es-discuss mailing list