This.ArrowFunctions
Aside from helping us shorten our code in JavaScript arrow functions =>
help us when we need to have the value of this
reference back to the original function when this
was first defined. For example if we have :
class Human {
constructor(name) {
this.name = name
} arrowFunction() {
setTimeout(() => {
console.log('arrow: ' + this.name)
}, 1)
} regularFunction() {
setTimeout(function() {
console.log('function: ' + this.name)
}, 1)
}
}human1 = new Human('John')
human1.arrowFunction() // arrow: John
human1.regularFunction() // function:
Even though both functions are in the same Human
class the one that was written as an arrow function successfully passed in the this.name
that we wanted it to return. But the regular function did not return the name it was just left blank. The reason is because regular functions bind
the this
keyword depending on where the function is being called. So because the regularFunction()
is being called outside of the Human
class it is automatically redefining the this
keyword to the global scope because regular functions in JavaScript redefine this
to whatever scope the function is being called in. The arrowFunction()
did not redefine this
to the global scope when it was called outside of the class, because arrow functions don’t redefine this
they use the scope from when the original arrowFunction()
was defined, which was inside of the Human
class. So even though human1.arrowFunction()
was also called outside in the global scope the same as human1.regularFunction()
, because one function was originally defined with an arrow function and the other as a regular function, this
had very different values. Building functions with the arrow function is helpful in the sense that it is better to have the value of this
be defined in the same scope where the function is being originally defined as opposed to where you call on the function.
When it comes to classes this
inside the constructor method will always reference the particular instance method. When we used new Human(‘John’)
the constructor method:
constructor(name) {
this.name = name
}
The constructor takes in the name of ‘John’ and for this instance of a Human that is being created this
refers to the new Human being created who’s name is ‘John’. this
inside a class will always reference the individual instance, so this is why arrow functions are useful, because we can use the value(s) of that instance method outside of the class scope that it was defined in.