Non-method functions and this

David Herman dherman at mozilla.com
Mon May 16 09:16:13 PDT 2011


> - "self" is just another parameter, it can be called anything.
> - Function.prototype.call() and Function.prototype.apply() would have one parameter less.
> - IIRC, this is more or less how Python works.
> - Probably not worth it, migration-cost-wise.

This breaks the web, so regardless of whether it's worth it, it's just not possible. Harmony and non-Harmony share a heap with the same built-in globals. If you change Function.prototype.call and Function.prototype.apply, you break the web.

> As an aside, I'm surprised that (ES5) JavaScript interprets the following as a method call:
> (obj.method)(arg)
> 
> It seems like the temporary result of the expression obj.method includes a value for "this" (which is lost after making the assignment func = obj.method).

That's not how the language is specified; there's no temporary variable introduced.

Briefly: ES has been specified since time immemorial with a fictional kind of value known as a "Reference." You can think of this as a first-class lvalue: it's a value that encapsulates a reference to an assignable location (in the heap, or possibly the stack, depending on the implementation). Many operations in the language automatically dereference a reference value, i.e. retrieve the value it points to, so most of the time these reference values aren't something a JS program can get its hand on directly. But paren expressions don't automatically dereference their result, they just pass reference values on through to their containing expression.

So in your example, the expression |obj.method| produces an "object reference" (roughly, a pointer to the |method| property of the |obj| object), and the paren expression just passes that object reference through to the call. The method call then uses the base object of the object reference, which is |obj|, as the |this|-binding.

Dave



More information about the es-discuss mailing list