Javascript arrow function WTF

I thought that JavaScript arrow functions are just a shorthand notation for regular functions. I was wrong, and I found it the hard way. Arrow function treat ‘this’ keyword differently.

var x = 3, y = 4;
var obj = { 
  x: 42, 
  y: 50, 
  length1: function() { return Math.sqrt(this.x*this.x+this.y*this.y); }, // this === obj
  length2: () =>               Math.sqrt(this.x*this.x+this.y*this.y),    // this === global
};

console.log('length1: ' + obj.length1());
console.log('length2: ' + obj.length2());

They explain it by stating that separate ‘this’ scope for callback functions was getting in the way, so they got rid of it for arrow functions. RTFM, RTFM, and once more RTFM.

Leave a Reply

Your email address will not be published. Required fields are marked *