1

下面的代码是有效的 JavaScript,但在 typescript 中它会引发以下错误。知道为什么吗?

错误 7 当前范围内不存在名称“gameloop”

(function gameloop() {
    window.requestAnimationFrame(gameloop);
})();

编辑:第一次回答后注意到与实际问题无关的复制和粘贴错误。

4

4 回答 4

4

知道了。错误与函数的范围有关。所以我需要这个

(function gameloop() {
window.requestAnimationFrame(this.gameloop);
})();

即使它在Javascript中符合这一点。

(function gameloop() {
window.requestAnimationFrame(gameloop);
})();
于 2012-10-21T17:01:45.087 回答
4

这只是一个缺少的分号,阻止它在 Javascript 和 Typescript 中都是正确的。

这应该工作:

   var game = new Game(); // <== don't forget ';' here
   (function gameloop() {

       // stats.update();
        game.step();
        game.update();
        game.draw();

        window.requestAnimationFrame(gameloop);
    })();

不要依赖自动分号插入:规则太复杂了。

在您的情况下,编译器看到

... new Game()(something) ...

并且没有足够的信息不认为这something是传递给函数的参数new Game()。因此错误...

于 2012-10-21T16:11:20.460 回答
3

我也遇到过这个问题,但它需要不同的修复。就我而言,我使用的是 TypeScript 中的 window.requestAnimationFrame,然后在 Chrome 上运行代码。但是,我得到一个运行时错误,“窗口没有 requestAnimationFrame”。这是因为 requestAnimationFrame 在 Chrome 中仍然是前缀。您要么需要在 TypeScript 声明中添加前缀声明,要么只需将 JavaScript 文件添加到您的项目中,以标准方式 plolyfills window.requestAnimationFrame;

// requestAnimFrame shim  with setTimeout fallback
window.requestAnimationFrame = (function () {
    return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function (callback) {
                window.setTimeout(callback, 1000 / 60);
            };
})();

我使用 polyfill 方法使 requestAnimationFrame 在 chrome 上工作,因为它是如此常见的修复。polyfill 本身可以用纯 TypeScript 编写,并带有一堆强制转换,但是 Javascript 干净且简单,当 Chrome 删除前缀时您可以将其删除,而不会影响您的 TypeScript。

于 2012-10-21T22:50:34.693 回答
1

Note also that there is an issue currently with calling a named function expression within said function expression, which may bite you in code similar to the above. Namely the below code will give you the error shown in the comments even though valid:

function a() {
    var x = function b() {
        b(); // <-- "**The name 'b' does not exist in the current scope**"
    }
}

This is valid as per section 13 of the ECMAScript spec, but fails currently.

于 2012-10-22T21:14:11.513 回答