This commit is contained in:
Ilya Kantor 2019-05-31 19:17:46 +03:00
parent 76b0616727
commit 9f4b8a5c98

View file

@ -166,7 +166,7 @@ If we used `this.name` instead of `user.name` inside the `alert`, then the code
## "this" is not bound
In JavaScript, "this" keyword behaves unlike most other programming languages. First, it can be used in any function.
In JavaScript, "this" keyword behaves unlike most other programming languages. It can be used in any function.
There's no syntax error in the code like that:
@ -176,9 +176,9 @@ function sayHi() {
}
```
The value of `this` is evaluated during the run-time. And it can be anything.
The value of `this` is evaluated during the run-time, depending on the context. And it can be anything.
For instance, the same function may have different "this" when called from different objects:
For instance, here the same function is assigned to two different objects and has different "this" in the calls:
```js run
let user = { name: "John" };
@ -189,7 +189,7 @@ function sayHi() {
}
*!*
// use the same functions in two objects
// use the same function in two objects
user.f = sayHi;
admin.f = sayHi;
*/!*
@ -202,7 +202,10 @@ admin.f(); // Admin (this == admin)
admin['f'](); // Admin (dot or square brackets access the method doesn't matter)
```
Actually, we can call the function without an object at all:
The rule is simple: if `obj.f()` is called, then `this` is `obj` during the call of `f`. So it's either `user` or `admin` in the example above.
```smart header="Calling without an object: `this=undefined`"
We can even call the function without an object at all:
```js run
function sayHi() {
@ -216,7 +219,8 @@ In this case `this` is `undefined` in strict mode. If we try to access `this.nam
In non-strict mode the value of `this` in such case will be the *global object* (`window` in a browser, we'll get to it later in the chapter [](info:global-object)). This is a historical behavior that `"use strict"` fixes.
Please note that usually a call of a function that uses `this` without an object is not normal, but rather a programming mistake. If a function has `this`, then it is usually meant to be called in the context of an object.
Usually such call is an programming error. If there's `this` inside a function, it expects to be called in an object context.
```
```smart header="The consequences of unbound `this`"
If you come from another programming language, then you are probably used to the idea of a "bound `this`", where methods defined in an object always have `this` referencing that object.