You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ES6类中requestAnimationFrame回调函数的this引用丢失问题咨询

解决ES6类中requestAnimationFrame回调无法获取this的问题

嘿,这个坑我之前踩过好几次!在ES6类里用requestAnimationFrame时,回调里的this默认不会指向类的实例——因为requestAnimationFrame是全局方法,它调用回调时会把this绑定到全局对象(浏览器里就是window,严格模式下是undefined)。下面给你几个实用的解决办法:

方法1:使用箭头函数

箭头函数不会创建自己的this,它会继承外层作用域的this,也就是类实例的引用。这种写法最简洁:

class AnimationController {
  start() {
    requestAnimationFrame(() => {
      // 这里的this就是AnimationController的实例
      console.log(this);
      this.render();
      // 如果是循环动画,继续调用
      requestAnimationFrame(() => this.render());
    });
  }

  render() {
    // 你的动画渲染逻辑
    console.log('执行动画帧');
  }
}

方法2:在构造函数中绑定this

如果你的回调是一个独立的类方法,可以在构造函数里用bind把方法的this永久绑定到类实例上,这样每次调用这个方法时this都不会跑偏:

class AnimationController {
  constructor() {
    // 把render方法的this绑定到当前实例
    this.render = this.render.bind(this);
  }

  start() {
    requestAnimationFrame(this.render);
  }

  render() {
    console.log(this); // 指向类实例
    // 循环动画的话直接递归调用即可
    requestAnimationFrame(this.render);
  }
}

方法3:使用类字段定义箭头函数(ES2022+)

如果你使用的环境支持ES2022的类字段语法,可以直接把方法定义成箭头函数,这样它的this会自动绑定到类实例:

class AnimationController {
  // 类字段形式的箭头函数,this自动绑定实例
  render = () => {
    console.log(this);
    requestAnimationFrame(this.render);
  }

  start() {
    requestAnimationFrame(this.render);
  }
}

为什么会出现这个问题?

本质是函数绑定丢失:当你把类的普通方法作为参数传给requestAnimationFrame时,这个方法会脱离类实例的上下文,调用时this就会指向全局对象(非严格模式)或undefined(严格模式)。上面的几种方法都是通过不同方式把this重新绑定到类实例上。

内容的提问来源于stack exchange,提问作者Eric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:08:32