9

Closed

Thin arrow lambda functions

description

Using the ECMAScript 6/TypeScript syntax for lambdas is annoying with JQuery and other libraries, as these libraries reassign the this pointer, which the fat arrow lambdas override.

It would be very useful to be able to also declare lambdas with thin arrow functions that don't maintain the this pointer of the outer scope. CoffeeScript uses this approach.

Instead of:
function foo()
{
  $('div').click(() => {
       var value = $(this).val();
      //Whoops! This isn't the "this" set by JQuery anymore!
  }
}
Have:
function foo()
{
  $('div').click(() -> {
       var value = $(this).val();
      //Now everything is good
  }
}
Closed Jul 28 at 11:18 PM by jonturner
As part of our move to GitHub, we're closing our CodePlex suggestions and asking that people move them to the GitHub issue tracker for further discussion. Some feature requests may already be active on GitHub, so please make sure to look for an existing issue before filing a new one.

You can find our GitHub issue tracker here:
https://github.com/microsoft/typeScript/issues

comments

paulb wrote Feb 13, 2013 at 7:15 PM

Thanks for reporting this. Assigned to Jon who manages our suggestions.

A workaround, which I'm sure you're aware of is using 'function' instead of the 'fat arrow'.

MgSam wrote Feb 13, 2013 at 8:09 PM

Thanks for taking the time to respond.

function is still available, but besides the word "function" being bulkier to write and read, it doesn't have the implicit brackets or return statement so it makes what could/should be a short little lambda into an ugly beast.

clausreinke wrote Feb 14, 2013 at 12:53 AM

Not that I'd recommend this, but you can hack your own thin arrow:-)
function thin(arr) {
    return function(...args:any) {
            return arr.apply(this,[this].concat([args]))
            }
}

var obj = {name:"obj"
          ,f:thin( (it,msg)=>it.name+" says "+msg )
          };

alert(obj.f("hello"));

_virtualvoid_ wrote Mar 8, 2013 at 9:45 PM

Besides the convenience, using '->' instead of 'function' also increases the code readability. Please consider add this feature, would be great!. Thanks.

WilliamMoy wrote Apr 11, 2013 at 6:02 AM

I think in terms of readability, -> is too similar to => and will easily be misread. The function() { } syntax is fine; it's basic JavaScript.