js requestAnimationFrame 使用疑惑?

class A {
  v = 1;
  output() {
    console.log(2233, this.v);
  }
  get1() {
    requestAnimationFrame(this.output);
  }
  get2() {
    requestAnimationFrame(() => this.output());
  }
}
var a = new A();
a.get1();
a.get2();

image.png

get1 方法为什么没有输出?


网页环境不同输出结果也不一致
上图是在谷歌翻译的控制台执行的
若是思否则会报 undefined :
image.png

阅读 652
avatarAI BotBETA

requestAnimationFrame 函数在调用时,会创建一个回调函数并将其放在下一次重绘之前执行。在这种情况下,它接受的参数是一个回调函数,并且这个回调函数会被自动执行,也就是说,this.output 会在没有显式调用的情况下被执行。

然而,当你尝试在 get1 方法中直接传递 this.output 作为 requestAnimationFrame 的参数时,会出现问题。这是因为在 JavaScript 中,this 的值是在函数被调用时确定的,而不是在函数被定义或传递时确定的。

因此,在 get1 方法中,this.output 被传递给了 requestAnimationFrame,但此时 this 的值已经改变(从 A 类的实例变为了全局对象,如 window),所以 this.output 实际上变成了 window.output,而 window 对象上并没有 output 方法,因此不会输出任何内容。

为了解决这个问题,你可以使用箭头函数(() =>)来创建一个新的函数,这个新函数会捕获 this 的当前值(即 A 类的实例),然后你可以将这个新函数传递给 requestAnimationFrame。这就是 get2 方法所做的。

所以,get1 方法没有输出,是因为 this 的值在 requestAnimationFrame 执行回调函数时发生了改变,导致 this.output 无法正确引用到 A 类的 output 方法。

2 个回答

臭名昭著的 this 问题。
可以这样写:

class A {
  v = 1;
  output = () => {
    console.log(2233, this.v);
  }
  get1 = () => {
    requestAnimationFrame(this.output);
  }
  get2() {
    requestAnimationFrame(() => this.output());
  }
}
var a = new A();
a.get1();
a.get2();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题