- To access the object, a method can use the
**this**
keyword.
- The value of
**this**
is the object “before dot”, or simply the one that call the method.
let user = {
name: "John",
age: 30,
sayHi() {
alert(this.name);
}
};
user.sayHi(); // John
- Technically, it’s also possible to access the object without this, by referencing it via the outer variable, but such code is unreliable as the reference name may change.
- In JavaScript, “
**this**
” keyword behaves unlike most other programming languages.
- First, it can be used in any function.
- The value of the following
**this**
is evaluated during the run-time and it can be anything.
function sayHi() {
console.log(this.name);
}
- Actually, we can call the function without an object at all.
- In the following case,
**this**
is **undefined**
in strict mode.
- If we try to access
**this.name**
, there will be an error.
- In non-strict mode, the value of
**this**
in such case will be the global object (window
in a browser).
- This is a historical behavior that
"use strict"
fixes.
- 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.
function sayHi() {
alert(this);
}
sayHi(); // undefined
**this**
and Reference Type
- An intricate method call can lose
**this**
reference.
let user = {
name: "John",
hi() { console.log(this.name); },
bye() { console.log("Bye"); }
};
user.hi(); // John
const targetMethod = (user.name === "John" ? user.hi : user.bye);
targetMethod(); // Undefined, because the context the method call is undefined.
- To make
**user.hi()**
or targetMethod()
calls work, JavaScript uses a trick:
- The
.
returns not a function, but a value of the special Reference Type.
- The Reference Type is a “specification type”, so we can’t explicitly use it, but it is used internally by the language.
- It is a three-value combination
**(base, name, strict)**
, where:
base
is the object.
name
is the property.
strict
is true if use strict
is in effect.
- Therefore, the result of a property access
user.hi
is not a function, but a value of Reference Type.
- When parentheses
()
are called on the Reference Type, they receive the full information about the object and its method.
Arrow Functions Have No “this
”
- Arrow functions are special: they don’t have their “own”
**this**
.
- If we reference
this
from such a function, it’s taken from the outer “normal” function.