javascript - 作为 window.requestAnimationFrame() 参数的回调函数

标签 javascript

我有一个 js 文件,我正在使用 requestAnimationFrame()。我知道参数应该是回调函数。我认为我的参数是回调函数,但错误来自 js 控制台:

TypeError: Argument 1 of Window.requestAnimationFrame is not an object.

文件.js:

function screen(){
     console.log("it works!")
}

function fun(word){
    if (word === 'tree'){
        screen()
    }
window.requestAnimationFrame(fun("tree"));

一切正常。我在我的大型项目中使用它并且一切正常,但我不知道为什么我在 js 控制台中出现错误

最佳答案

您将 fun 函数的执行结果传递给 requestAnimationFrame,这就是您收到错误的原因(因为它返回未定义)。

正确的做法:

function screen(){
     console.log("it works!")
}

function fun(word){
    if (word === 'tree'){
        screen()
    }
}
window.requestAnimationFrame(fun.bind(window, "tree"));

有关bind 的更多信息,您可以在documentation 中找到.

关于javascript - 作为 window.requestAnimationFrame() 参数的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48086337/

相关文章:

javascript - 如何使用JS函数动态更改列表的类

javascript - $ ("<img/>").attr ("src",something).load() 在 IE < 9 中不支持?

javascript - react : e. 目标。?日志未定义

javascript - 使用密码连接数据库的最佳方式是什么?

javascript - canplaythrough 事件和 HTM5 音频 : can anyone remove this event?

javascript - 覆盖 Zurb Foundation 5 更改全局清除默认模板

javascript - 根据坐标识别顺序

javascript - 在 jQuery datetimepicker 中禁用特定日期之后的所有日期

javascript - 表达 : typescript: Argument of type 'typeof <express.Router>' is not assignable to parameter of type 'RequestHandlerParams'

javascript - 在播放幻灯片时访问视频剪辑时间标记