本文深入探讨了在javascript中创建可自驱动动画对象的常见挑战,特别是当使用`settimeout`或`setinterval`时`this`上下文丢失的问题。文章详细解释了`this`指向`window`对象的原因,并提供了两种有效的解决方案:利用es6箭头函数的词法作用域`this`绑定,以及使用`function.prototype.bind()`方法显式绑定`this`。通过示例代码,读者将学会如何构建结构清晰、性能优化的自驱动动画组件。
在JavaScript中,我们经常需要创建能够独立执行行为的对象,尤其是在图形和动画场景中。例如,一个“盒子”对象可能需要自己管理其位置并在画布上移动。然而,在实现这类自驱动动画时,一个常见的陷阱是this上下文的丢失,这会导致对象的方法无法正确访问其自身的属性。本教程将详细解析这一问题,并提供两种健壮的解决方案。
考虑以下场景,我们尝试创建一个SelfMovingBox对象,它包含一个animate方法,该方法通过setTimeout递归调用自身以实现动画效果。
const Canvas = document.getElementById("diagramCanvas");
const CanvasContext = Canvas.getContext('2d');
const width = Canvas.width, height = Canvas.height;
function SelfMovingBox() {
this.x = width; // 初始位置
this.y = 10;
this.width = 100;
this.height = 20;
this.speed = 10;
this.animate = function() {
// 在第一次调用时,this指向SelfMovingBox实例
// 但在setTimeout回调中,this会指向全局对象(Window)
CanvasContext.clearRect(this.x, this.y, this.width, this.height); // 清除旧位置
this.x -= this.speed; // 更新位置
// 检查是否超出边界,如果超出则停止或重置
if (this.x + this.width < 0) {
console.log("Box out of bounds, stopping animation.");
return; // 停止动画
}
CanvasContext.save();
CanvasContext.strokeStyle = 'blue';
CanvasContext.strokeRect(this.x, this.y, this.width, this.height); // 绘制新位置
CanvasContext.restore();
// 关键问题所在:setTimeout的回调函数中,this的指向会改变
setTimeout(this.animate, 100);
};
}
// 假设HTML中有一个元素
// let box = new SelfMovingBox();
// box.animate(); // 首次调用时正常,但setTimeout中的this会出错当box.animate()首次被调用时,this确实指向SelfMovingBox的实例,因此this.x等属性可以被正确访问。然而,当setTimeout(this.animate, 100)被执行时,this.animate方法被作为回调函数传递给了setTimeout。在非严格模式下,当一个函数作为普通函数调用(而不是作为对象的方法调用,也不是通过new调用)时,其内部的this会默认指向全局对象(在浏览器环境中是Window对象)。
这意味着,在setTimeout内部再次执行this.animate时,this.x、this.y等实际上是在尝试访问Window.x、Window.y,这些属性通常是不存在的或不相关的,导致动画无法继续或行为异常,且不会抛出显式错误。
ES6引入的箭头函数提供了一种更简洁的方式来处理this上下文。箭头函数没有自己的this绑定,它们会捕获其所在上下文的this值。这意味着,在定义animate方法时使用箭头函数,this将始终指向SelfMovingBox实例。
function SelfMovingBoxArrow() {
this.x = width;
this.y = 10;
this.width = 100;
this.height = 20;
this.speed = 10;
// 使用箭头函数定义animate方法
this.animate = () => {
CanvasContext.clearRect(this.x, this.y, this.width, this.height);
this.x -= this.speed;
if (this.x + this.width < 0) {
console.log("Box out of bounds, stopping animation.");
return;
}
CanvasContext.save();
CanvasContext.strokeStyle = 'blue';
CanvasContext.strokeRect(this.x, this.y, this.width, this.height);
CanvasContext.restore();
// 这里的this仍然指向SelfMovingBox实例
setTimeout(this.animate, 100);
};
}
// let boxArrow = new SelfMovingBoxArrow();
// boxArrow.animate(); // 现在动画将正常循环通过将this.animate定义为一个箭头函数,它会“记住”其创建时所处的SelfMovingBox实例的this。无论animate方法在何处被调用,其内部的this都将保持不变,从而正确访问对象的属性。
bind()方法是JavaScript中用于显式绑定函数this上下文的另一个强大工具。它会创建一个新的函数,当这个新函数被调用时,其this关键字会被设置为提供的值。
function SelfMovingBoxBind() {
this.x = width;
this.y = 10;
this.width = 100;
this.height = 20;
this.speed = 10;
// 定义animate方法,并立即绑定this
this.animate = (function() {
CanvasContext.clearRect(this.x, this.y, this.width, this.height);
this.x -= this.speed;
if (this.x + this.width < 0) {
console.log("Box out of bounds, stopping animation.");
return;
}
CanvasContext.save();
CanvasContext.strokeStyle = 'blue';
CanvasContext.strokeRect(this.x, this.y, this.width, this.height);
CanvasContext.restore();
// 这里的this仍然指向SelfMovingBox实例
setTimeout(this.animate, 100);
}).bind(this); // 在定义时就将animate方法的this绑定到当前的SelfMovingBox实例
}
// let boxBind = new SelfMovingBoxBind();
// boxBind.animate(); // 动画也将正常循环在这个例子中,this.animate = (function() { ... }).bind(this);这行代码在SelfMovingBoxBind构造函数内部,将匿名函数中的this永久地绑定到当前SelfMovingBoxBind实例的this。这样,即使setTimeout以普通函数调用的方式执行this.animate,其内部的this也已经被强制指向了正确的实例。
为了提供一个完整的、可运行的示例,并结合一些动画的最佳实践,我们将使用箭头函数方案并引入requestAnimationFrame以获得更平滑的动画效果。requestAnimationFrame是浏览器专门为动画优化的API,它会在浏览器准备好绘制下一帧时调用回调函数,从而避免掉帧和性能问题。
JavaScript 自驱动动画对象
注意事项与总结:
通过本文的讲解和示例,您应该能够清晰地理解JavaScript中this上下文在自驱动动画中的作用,并掌握使用箭头函数或bind()方法来解决这一问题的技巧,从而创建出功能完善、性能优化的动画组件。