JavaScript this错乱问题分析
首先观察一段实现倒数功能的类「Countdown」及其实例化过程的代码:
function Countdown(seconds) {
this._seconds = seconds;
}
Countdown.prototype._step = function() {
console.log(this._seconds);
if (this._seconds > 0) {
this._seconds -= 1;
} else {
clearInterval(this._timer);
}
};
Countdown.prototype.start = function() {
this._step();
this._timer = setInterval(function() {
this._step();
}, 1000);
};
new Countdown(10).start();
执行上述代码时,系统会抛出异常「this._step is not a function」。
这反映了JavaScript中常见的「this错乱」现象:在setInterval周期性执行的回调函数内,this的值已与外部环境的this不再一致。
针对此问题,存在三种主要的解决思路。
闭包方案
通过定义一个新变量来引用期望的this对象,并将该变量置于闭包作用域内:
Countdown.prototype.start = function() {
var self = this;
this._step();
this._timer = setInterval(function() {
self._step();
}, 1000);
};
bind函数方案
ES5规范为函数类型引入了「bind」方法,该方法能够改变函数的this绑定(实际返回一个绑定了新this的新函数):
Countdown.prototype.start = function() {
this._step();
this._timer = setInterval(function() {
this._step();
}.bind(this), 1000);
};
箭头函数方案
这正是本文着重探讨的解决途径。作为ES6引入的新语法特性,箭头函数不仅在形式上精简了匿名函数的书写,更关键的是它具备特殊的this绑定行为——箭头函数会捕获其定义时所在上下文的this值作为自身的this。这意味着箭头函数内部与其外部的this保持完全一致。
基于此特性,解决方案可改写为:
Countdown.prototype.start = function() {
this._step();
this._timer = setInterval(() => {
this._step();
}, 1000);
};
这种方式显著简化了this的处理逻辑。但对于JavaScript开发者而言,判断this指向的场景又多了一种需要考量的情况。
总结
以上内容涵盖了本文的核心知识点,希望能对各位的学习或工作有所助益。如有任何疑问,欢迎留言交流。