The other "this" for arrow function

the point of introducing arrow functions was to provide a nifty and less chatty syntax for functions. it is adapted by masses. yet, there is one case which language doesn't allow.

today, this works

String.prototype.test = function (v1, v2) { return this.replace(v1, v2); }

but this doesn't

String.prototype.test = (v1, v2) => this.replace(v1, v2); 

because this in arrow function belongs to the location of object literal not the function context.

extending the conciseness aspect of arrow function to also allow contextual this is the next best thing.

proposal: some people call arrow function "thick arrow", so maybe the thin arrow -> syntax be the right syntax for it? i'm not sure because i'm not a language designer, so i don't know what would be the best equally concise syntax. i just hope to see "some way" to extend arrow to cover this last piece of puzzle so we can completely get rid of function { return } parts from source code.

Why is getting rid of that a valuable goal?

1 Like

one of the goal of why arrow functions were added to language in the first place was Shorter syntactical form. this proposal is to extend that goal so the new syntax (whatever that may be) will just be a short sugar for regular function that will support all regular function characteristics which are missing from thick arrow functions i.e. "thin arrow functions" to have their own this binding, allow yield statements, allow different this with call/bind etc.

Specifically, for callbacks, where a lexical this was needed. Regular functions don't need shorter syntax, and this-sensitive functions are pretty out of vogue anyways.

See:

2 Likes