Non-method functions and this

Brendan Eich brendan at mozilla.com
Sun May 15 13:47:08 PDT 2011


On May 15, 2011, at 1:09 PM, Axel Rauschmayer wrote:

> Sorry for bringing this up again, but I don’t think this particular question has been answered yet:
> 
> (1) I would prefer non-method functions not to have a binding for |this| at all.

How do you define "non-method"?

It would make an early error for many functions written today as function declarations, which use |this| because they are assigned as property values (i.e. as methods), to call the |this| usage in such functions an early error. That would be a harsh migration tax, even though compile-time. We are not changing Harmony that much.

On the other hand, if you mean a runtime error, that's right out as an untestable migration booby trap.


> (2) The solution for ES.next seems to be to (e.g. internally, via =>) bind to |this| of the surrounding method.

The http://wiki.ecmascript.org/doku.php?id=strawman:arrow_function_syntax proposal is still a strawman. Whatever we do, lexical |this| is wanted, for the

  function outer () {
    var self = this;
    return function () {... self ...};
  }

cliché. This is too common a pattern to ignore.


> Isn’t (1) a better solution?

Why?

Again, what's a "non-method function"?


> I’m assuming (2) is done, because (1) would be too radical a change (execution contexts etc.)?

Think migration tax. Many functions whether declared or expressed use |this| today. They are used as methods but the linkage to their method name (property of an object) is not declared or even expressed nearby. How would you forbid such functions to use |this|, or allow them to but forbid others that are not called as methods to use |this|/


> (1) could be simulated by always binding |this| in non-method functions, but that isn’t done because of performance issues(?)

There is no "non-method function" in JS today. You are thinking of call expressions, how |this| is bound dynamically. Programmer intent is not expressible directly in the language, and whatever extensions we add (e.g. for methods in object intiialisers, proposed in several strawmen), we aren't going to break the existing code that declares and expresses functions that use |this|.

/be
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110515/2ecbca2d/attachment.html>


More information about the es-discuss mailing list