this 由函数是如何被调用的决定,而不是它在哪里定义的。有五条规则:
js
const obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this 由函数是如何被调用的决定,而不是它在哪里定义的。有五条规则:
const obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
箭头函数没有自己的 this — 它们在定义时从周围作用域继承它。这就是为什么箭头函数非常适合作为回调函数:
const obj = {
items: [1, 2],
logAll() {
// ✅ arrow inherits `this` from logAll → `this` is obj
this.items.forEach(i => console.log(this.items, i));
// ❌ a regular function here would have its own `this` (undefined) → crash
// this.items.forEach(function (i) { console.log(this.items); });
},
};
将方法作为回调函数传递会失去它的绑定,因为之后它被普通地调用:
button.addEventListener("click", obj.getX); // ❌ `this` is the button
button.addEventListener("click", () => obj.getX()); // ✅ keeps obj
button.addEventListener("click", obj.getX.bind(obj)); // ✅ also fine
误解 this 是最常见的 JS bug 之一。
修复通常是使用箭头函数或 .bind() 来锁定所需的 this。