Non-method functions and this

Axel Rauschmayer axel at rauschma.de
Sun May 15 14:36:31 PDT 2011


Caveat: I am aware that what I’m suggesting might clash too hardly with current semantics (how to handle invocation, apply(), call(), etc.), but I am interested in the arguments against it.

>> (1) I would prefer non-method functions not to have a binding for |this| at all.
> 
> 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.

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

Right. It could be introduced via the arrow function syntax, with the "function" operator remaining as is:

var obj = {
    id: "123",
    method: (x) => {  // same as function operator
        [1,2].forEach((i) -> {  // new construct
            console.log(this.id + ": " + i + " - " + x);
        });
    }
}

Thus:
=> and function: |this| is an implicit argument (“methods”)
->: |this| is not an implicit argument; currently simulated via binding (“functions”)

The arrows are swapped compared to the strawman, because => is more “heavy-weight” here.

>> Isn’t (1) a better solution?
> 
> Why?

It is easier to understand for beginners. |this| always being an implicit parameter trips up many newbies. I also find it a cleaner way of getting lexical |this|.

>> 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|/

See above.

Greetings,

Axel

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list