Non-method functions and this

Axel Rauschmayer axel at rauschma.de
Sun May 15 16:19:20 PDT 2011


>>> Oh, I see. But there's still a problem. Without a class or similar declarative form to associate the method with an object or class of objects, making the function syntax reject or accept |this| in the function body is not enough. A method needs to be enclosed by a class.
>>> 
>>> We have proposals to do that, and for such methods, |this| binding should be unsurprising and trouble-free.
>> 
>> Interesting. I thought that functions were methods (=dynamic |this|) by default and that function definitions nested inside them were the problem (=extra work via bind() to get lexical this).
> 
> Nested functions not called as method are a use-case for lexical-|this|, met poorly today via .bind(this) or equivalent. Yes, that's true -- does that lead back to which arrow should be "fat" vs. "thin"? I don't see how it otherwise bears on things.
> 
> We want one arrow-function form to inherit lexical |this|, the other to have dynamic-|this|. The full strawman even allows "soft binding" of |this| via explicit (this ??= default_this) parameterization. But in any event, the only question is what syntax to choose for the several kinds of |this| binding. Right?

Right. The heavy arrow correctly visualizes the “extra work” (of binding/lexical |this|). I thought the proposal that you talked about did something more “clever” (e.g. change the semantics of functions that are sure to be methods). But given all of the constraints (migration tax, heavy-weight lexical |this|, existing function semantics, etc.), I don’t see how one could do better than the strawman. I especially like how arrow function literals look in object literals.

>> I assume that the proposal changes functions nested inside methods, to have lexical |this| by default (unless they are again enclosed by a class). Or is changing the |this| handling for nested functions what you mean by “methods”?
> 
> The arrow proposal changes nothing by default, it just provides sugar. If you are nesting an arrow in another function and want to inherit the outer function's |this|, use =>. Else use ->, or perhaps an explicit (this = ...) parameter.

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list