javascript中this丢失时,可用中间变量(如that)、箭头函数、bind或class箭头属性四种方式绑定:前者兼容性好,后三者更简洁清晰,推荐es6+用箭头函数或bind。

在 JavaScript 中,当函数被作为回调或事件处理器调用时,this 的指向常常会丢失(比如变成 undefined 或全局对象)。为保留原始上下文,常用做法是用中间变量(如 self、that 或 _this)在外部作用域缓存当前的 this 值。
用 var that = this 在函数外保存
这是最经典、兼容性最好的方式,尤其适用于 ES5 及更早环境:
说明:在调用函数的初始作用域中,把 this 赋给一个变量,然后在内部函数里引用它。
示例:
function Counter() {
this.count = 0;
var that = this; // 缓存 this
document.addEventListener('click', function() {
that.count++; // 使用 that,而非 this
console.log(that.count);
});
}
用箭头函数自动绑定 this(ES6+ 推荐)
箭头函数不创建自己的 this,而是继承外层作用域的 this,因此无需手动保存中间变量:
说明:只要外层函数的 this 是你期望的(比如类方法或构造函数中),箭头函数就能“自动”保持它。
示例:
function Counter() {
this.count = 0;
document.addEventListener('click', () => {
this.count++; // this 指向 Counter 实例
console.log(this.count);
});
}
用 bind 显式绑定 this
通过 Function.prototype.bind 创建一个永久绑定 this 的新函数:
说明:bind 返回的新函数,无论怎么调用,this 都固定为你传入的对象。
示例:
function Counter() {
this.count = 0;
document.addEventListener('click', function() {
this.count++;
console.log(this.count);
}.bind(this)); // 绑定 this 到当前实例
}
现代替代方案:class + 箭头属性(React 等常见写法)
在 ES6 class 中,可直接将方法定义为箭头函数属性,避免 this 丢失:
说明:类字段语法(需支持或转译)让方法天然绑定实例,适合事件处理器、定时器等场景。
示例:
class Counter {
constructor() {
this.count = 0;
document.addEventListener('click', this.handleClick);
}
handleClick = () => {
this.count++;
console.log(this.count);
};
}
不复杂但容易忽略——关键在于明确函数执行时 this 的来源,并选择合适的方式维持它。传统中间变量仍有效,但箭头函数和 bind 更简洁、语义更清晰。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











