Search code examples
javascriptthisecmascript-6arrow-functions

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


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();


Solution

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