本文共 392 字,大约阅读时间需要 1 分钟。
在 JavaScript 中,setInterval 和 setTimeout 函数将 callback 给定 window 对象作为调用上下文,因此在 callback 中的 this 会指向 window 对象。为了确保 this 指向目标对象(如 LateBloomer 实例),可以使用以下方法:
使用 bind 方法:
this 绑定到目标对象,确保在 callback 中正确使用。 window.setTimeout(this.declare.bind(this), 2000);
使用 ES6 箭头函数:
箭头函数的this 绑定定义时所在的上下文,避免使用 bind。 window.setTimeout(() => this.declare(), 2000);
确保选择的方法不会立即执行 declare(),否则延迟效果将失效。两种方法均可实现正确的绑定。
转载地址:http://pgqfk.baihongyu.com/