Từ khóa this, call, apply và bind
Với hàm thường, this được quyết định lúc gọi, không phải lúc khai báo.
4 quy tắc (hàm thường)
| Cách gọi | this là |
|---|---|
obj.method() | obj |
fn() (strict mode) | undefined |
fn.call(x), fn.apply(x), fn.bind(x)() | x |
new Fn() | object mới được tạo |
const user = {
name: "An",
hello() {
return `Tôi là ${this.name}`;
},
};
user.hello(); // "Tôi là An"
const fn = user.hello;
fn(); // TypeError: Cannot read properties of undefinedLỗi "mất this" rất hay gặp khi truyền method làm callback: setTimeout(user.hello, 100), button.addEventListener("click", obj.handle).
Arrow function không có this riêng
Arrow function lấy this của phạm vi bao quanh — rất hợp cho callback bên trong method:
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // this = timer
}, 1000);
},
};WARNING
Vì vậy không dùng arrow function làm method của object:
const bad = { name: "X", hello: () => this.name }; // this không phải badcall, apply, bind
function introduce(greeting, punctuation) {
return `${greeting}, tôi là ${this.name}${punctuation}`;
}
const an = { name: "An" };
introduce.call(an, "Chào", "!"); // gọi ngay, đối số rời
introduce.apply(an, ["Chào", "!"]); // gọi ngay, đối số là mảng
const bound = introduce.bind(an, "Hi");
bound("?"); // "Hi, tôi là An?"Sửa lỗi mất this
setTimeout(() => user.hello(), 100); // bọc trong arrow
setTimeout(user.hello.bind(user), 100); // hoặc bindTrong class, cách phổ biến là khai báo method dạng class field arrow (chương 7):
class Counter {
count = 0;
increment = () => { this.count++; };
}
Comments