What does "this" refer to in arrow functions in ES6?

temporary_user_name picture temporary_user_name · Feb 6, 2015 · Viewed 14.8k times · Source

I've read in several places that the key difference is that this is lexically bound in arrow functions. That's all well and good, but I don't actually know what that means.

I know it means it's unique within the confines of the braces defining the function's body, but I couldn't actually tell you the output of the following code, because I have no idea what this is referring to, unless it's referring to the fat arrow function itself....which doesn't seem useful.

var testFunction = () => { console.log(this) };
testFunction();

Answer

Dave picture Dave · Feb 6, 2015

Arrow functions capture the this value of the enclosing context

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

So, to directly answer your question, this inside your arrow function would have the same value as it did right before the arrow function was assigned.