上QQ阅读APP看书,第一时间看更新
Handling this in arrow functions
A well-known JS problem is how to handle this, because its value isn't always what you expect! Modern JS solves this with arrow functions that, unlike common functions, inherit the proper this value. A well-known example is as follows: you would expect the following code to display JAVASCRIPT after a few seconds, but rather undefined will be shown (don't mind the fact that you could have coded show() in a simpler way; I wanted to highlight a general problem and not a particular solution):
// Source file: src/arrow_functions.js
function Show(value: mixed): void {
this.saved = value;
setTimeout(function() {
console.log(this.saved);
}, 1000);
}
let w = new Show("Doesn't work..."); // instead, "undefined" is shown
There are three ways of solving this:
- Using .bind() to properly bind the timeout function to the correct value of this
- Using a closure and defining a local variable (usually called that) to store and save the original value of this
- Using arrow functions, which will work without any extra work
We can see these three solutions in the following code:
// Source file: src/arrow_functions.js
function Show1(value: mixed): void {
this.saved = value;
setTimeout(
function() {
console.log(this.saved);
}.bind(this),
1000
);
}
function Show2(value: mixed): void {
this.saved = value;
const that = this;
setTimeout(function() {
console.log(that.saved);
}, 2000);
}
function Show3(value: mixed): void {
this.saved = value;
setTimeout(() => {
console.log(this.saved);
}, 3000);
}
let x = new Show1("This");
let y = new Show2("always");
let z = new Show3("works");
We will get to see the .bind() idea in React in the Defining Components section of Chapter 6, Developing with React, where we will deal with this related problems.