Non-method functions and this

Axel Rauschmayer axel at rauschma.de
Mon May 16 08:35:33 PDT 2011


Yeah, sorry, I was wrong about the need for two constructs.

Example code:

> var obj = {
>     id: "ac3fb",
>     method: function(self, msgs) {
>         msgs.forEach(function(msg) {
>             console.log(self.id+": "+msg);
>         });
>     }
> };
> 
> // Invoke as method
> obj.method([ "hello", "world" ]);
> 
> // Invoke as function
> var func = obj.method;
> func(obj, [ "hello", "world" ]);


Notes:
- "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.

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).

On May 16, 2011, at 16:15 , David Herman wrote:

>>> How do you define "non-method"?
>> 
>> A function that is not invoked as method. Right now, the same kind of construct is used for both true functions and methods. I’m proposing a new construct (similar to the distinction that Python makes): a function that does not have an implicit |this| parameter.
> 
> Hm, you've lost me... [...]

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110516/42caec9a/attachment-0001.html>


More information about the es-discuss mailing list