【问题标题】:"Uncaught TypeError: number is not a function" - JavaScript object returns two types?“未捕获的 TypeError:数字不是函数” - JavaScript 对象返回两种类型?
【发布时间】:2015-03-23 21:50:41
【问题描述】:

我正在创建一个使用 HTML5 Canvas 将几何图形绘制到窗口的站点。我有一个“绘图”函数,我将它传递给一个使用 requestAnimationFrame 命令的函数,如下所示:

function animate(drawMe) {
  var requestAnimationFrame =  
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function(callback) {
      return setTimeout(callback, 10);
    };

  //draw the function that has been passed through
  drawMe();

  requestAnimationFrame(animate);
}

但请检查一下:当我调用“drawMe();”时在上面的代码中,通过的函数执行得很好,但也给了我错误“Uncaught TypeError: number is not a function”。如果我包含“console.log(typeof drawMe);”行控制台会打印出两个结果,“function”和“number”。

例如,我可以有一个非常简单的函数:

drawloop1 = function() {
  //draws a Rect to my canvas context
  cxt.drawRect(0,0,100,100);
}

为了确保我做对了,我运行“console.log(typeof drawloop1);”这会打印出“功能”,这是我所期望的。然后我将它传递给我的动画函数,如下所示:

animate(drawloop1);

这似乎很简单。但是一旦它被传递到“animate”中,它就会开始返回“function”和“number”。它按预期工作,但也会引发 TypeError。我试过不同的变量名,怕某处有重复的变量。有人可以向我解释这里发生了什么吗?

【问题讨论】:

    标签: javascript html animation canvas typeerror


    【解决方案1】:

    问题在于这一行:

    requestAnimationFrame(animate);
    

    ...告诉requestAnimationFrame 调用animate() 函数,但requestAnimationFrame 不知道将drawMe 作为参数传递。事实上,它作为参数传递的一个数字,一个DOMHighResTimeStamp,就像documented by MDN

    控制台会打印出两个结果,“function”和“number”。

    这不是同一调用的两个结果。它是第一次调用成功的一个日志,然后是第二个失败的第二个调用的第二个日志。

    第一次时间animate() 运行,当你直接调用它时,drawMe 实际上确实引用了一个它可以调用的函数。 时间animate()requestAnimationFrame()调用时运行,drawMe参数是一个数字。

    想到的第一种解决方法如下:

    function animate(drawMe) {
      var requestAnimationFrame =  
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        function(callback) {
          return setTimeout(callback, 10);
        };
    
      (function nextFrame() {
        drawMe();
        requestAnimationFrame(nextFrame);
      })();
    }
    

    也就是说,在animate() 中创建一个可以访问animate() 参数的本地函数,并将该本地函数传递给requestAnimationFrame()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      相关资源
      最近更新 更多