Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 881
temporary_user_name Avatar asked Feb 06 '15 18:02

temporary_user_name


People also ask

What is this in ES6?

While in ES5 'this' referred to the parent of the function, in ES6, arrow functions use lexical scoping — 'this' refers to it's current surrounding scope and no further. Thus the inner function knew to bind to the inner function only, and not to the object's method or the object itself.

Why we cant use this in arrow function?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

What is a lexical this?

Lexical this simply means that this is looked up in lexical scope.

What is this in JS?

What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.


1 Answers

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.

like image 81
Dave Avatar answered Oct 05 '22 00:10

Dave