What does “this” refer to in arrow functions in ES6?

  1. Home
  2. javascript
  3. 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();

First answer

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.

Second answer

Hope this code show could give you clearer idea. Basically, ‘this’ in arrow function is the current context version of ‘this’. See the code:

// 'this' in normal function & arrow function
var this1 = {
    number: 123,
    logFunction: function () { console.log(this); },
    logArrow: () => console.log(this)
};
this1.logFunction(); // Object { number: 123}
this1.logArrow(); // Window 

Third answer

Arrow function this is pointing to the surrounding parent in Es6, means it doesn’t scope like anonymous functions in ES5…

It’s very useful way to avoid assigning var self to this which is widely used in ES5…

Look at the example below, assigning a function inside an object:

var checkThis = {
  normalFunction: function () { console.log(this); },
  arrowFunction: () => console.log(this)
};

checkThis.normalFunction(); //Object {}
checkThis.arrowFunction(); //Window {external: Object, chrome: Object, document: document, tmpDebug: "", j: 0…}
Reprint:https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6
Spread the love

Related articles

Comments are closed.