This commit is contained in:
Ilya Kantor 2019-08-01 13:50:55 +03:00
parent d9075008f8
commit e6e562040d
5 changed files with 71 additions and 107 deletions

View file

@ -5,13 +5,13 @@ libs:
# Function binding
When using `setTimeout` with object methods or passing object methods along, there's a known problem: "losing `this`".
When passing object methods as callbacks, for instance to `setTimeout`, there's a known problem: "losing `this`".
Suddenly, `this` just stops working right. The situation is typical for novice developers, but happens with experienced ones as well.
In this chapter we'll see the ways to fix it.
## Losing "this"
We already know that in JavaScript it's easy to lose `this`. Once a method is passed somewhere separately from the object -- `this` is lost.
We've already seen examples of losing `this`. Once a method is passed somewhere separately from the object -- `this` is lost.
Here's how it may happen with `setTimeout`:
@ -37,7 +37,7 @@ let f = user.sayHi;
setTimeout(f, 1000); // lost user context
```
The method `setTimeout` in-browser is a little special: it sets `this=window` for the function call (for Node.js, `this` becomes the timer object, but doesn't really matter here). So for `this.firstName` it tries to get `window.firstName`, which does not exist. In other similar cases as we'll see, usually `this` just becomes `undefined`.
The method `setTimeout` in-browser is a little special: it sets `this=window` for the function call (for Node.js, `this` becomes the timer object, but doesn't really matter here). So for `this.firstName` it tries to get `window.firstName`, which does not exist. In other similar cases, usually `this` just becomes `undefined`.
The task is quite typical -- we want to pass an object method somewhere else (here -- to the scheduler) where it will be called. How to make sure that it will be called in the right context?