What does this refer to in arrow functions in ES6?
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.
this keyword in arrow function
Arrow functions have a lexical this
which means that the value of this
inside the function is the same as the value of this
outside the function.
It does not mean that this
points to an object containing all the variables from outside the function.
const anObject = {
aValue: "example value",
aMethod: function() {
console.log("aMethod", this.aValue);
const arrow = () => {
console.log("arrow", this.aValue);
}
arrow();
}
}
anObject.aMethod();
const copyOfAMethod = anObject.aMethod;
copyOfAMethod();
Could someone explain arrow functions? (ES6)
In the first example if you wouldn't use bind()
, then this
would refer to the setTimeout
callback. Because you used .bind()
you changed the this
reference to the obj
object. That's why you got the 42
as this.id
.
In the second example, bind()
is not required because arrow function does not have its own this
, it's the same as the parent this
, so in this case it's pointing to the obj
object and that's why you also get 42
as the this.id
ES6 arrow function and this context
Arrow functions are more or less equivalent to function
statements, except that they bind the this
argument to that of the parent scope.
In other words, if an arrow function appears in the top scope, its this
argument will always refer to the global scope (e.g., window
in browsers or global
in node.js), while an arrow function inside a regular function will have its this
argument the same as its outer function, as your code demostrates.
How to use context parameter of the filter() array with an arrow function
This happens because lambda functions (arrow) get the context of where they're defined, in this case Window
, which doesn't have lower
or upper
props. Just use range.upper
and range.lower
instead of this
and should work just fine.
Related Topics
When Is .Then(Success, Fail) Considered an Antipattern For Promises
Detecting an Undefined Object Property
Get Image Data Url in JavaScript
How to Use Formdata For Ajax File Upload
How to Add a Key/Value Pair to a JavaScript Object
Modifying a Copy of a JavaScript Object Is Causing the Original Object to Change
Question Mark and Colon in JavaScript
JavaScript - Sort Array Based on Another Array
How to Create an Accurate Timer in JavaScript
Programmatically Navigate Using React-Router
What Is the !! (Not Not) Operator in JavaScript
Persist Variables Between Page Loads
Share Data Between Angularjs Controllers
What Does the Exclamation Mark Do Before the Function
How to Update Nested State Properties in React
JavaScript or (||) Variable Assignment Explanation