Lexical versus dynamic "this"

Axel Rauschmayer axel at rauschma.de
Tue May 10 19:10:33 PDT 2011

>>> myfunc(param1, param2) -> { ... } // lexical this
>>> var obj = {
>>>   mymethod: (this, param1, param2) -> { ... } // dynamic this
>>> }
>> This is how Python handles methods. I think there were objections to this approach, but unfortunately I can neither remember them nor find them online.
> No, this was still a possibility and I almost wrote it up at http://wiki.ecmascript.org/doku.php?id=strawman:arrow_function_syntax -- but with (this) -> .... That was just gratuitously overlong and incompatible with CoffeeScript.
> There's no arguing with the objection that => feels to close to -> and lexical-this is a major change deserving more significant syntactic differentiation. It's plausible, but if users often need the heavier syntax, they'll waste keystrokes and brain cells on it and curse us for not getting the "right default".
> Usability is hard. I've seen zero evidence that CoffeeScript's fat-arrow is unusably terse and people are fooled into thinking it's as cheap as -> (if that's the concern). What is the problem?

I’m not emotionally invested in the explicit |this|. I know it from Python and Lua and like it there. It is also a nice visualization of the "shadowing" of |this|, in a way that should be easier to understand for newcomers.

On the other hand, CoffeeScript compatibility and terseness *are* valid arguments. Typing |this| for each method will be repetitive.

BTW: I find that the infix -> works well for object literals, where a prefix operator unnecessarily separates the method name from the parameter list.

To sum up: I don't lean either way, both solutions have pros and cons. Any solution that makes function expressions shorter is fine with me.

Another question: I find it conceptually clearer to distinguish between methods and functions, instead of between functions and functions with bound |this|. Wouldn’t it be better to use "->" for functions ("lighter", no |this| except for lexical access to |this|) and "=>" for methods ("heavier", |this| as an implicit parameter). Or does that deviate too much from current ES semantics?


Dr. Axel Rauschmayer

axel at rauschma.de

home: rauschma.de
blog: 2ality.com

More information about the es-discuss mailing list