首页 > 解决方案 > 使用 JavaScript 在 HTML 中找不到变量

问题描述

我正在构建一个网络应用程序(游戏)。我试图在我的主 html 文件中从“js/game”中调用一个游戏函数。不知何故 - 它无法链接,因为控制台给我一个错误。给出“找不到变量:游戏”

我玩过“游戏文件”,将其作为类,导出,更改。检查了所有内容,仍然无法发现错误。

游戏.js:  

``` let Game = function() {

    constructor(canvas, context) {
    // this.config = config; // customization
    this.canvas = canvas;
    this.context = context;
```

头部HTML:

<script src="js/game.js"></script>

<script>$(document).ready(function () {
        $("#high-scores-page").hide();
        $("#about-page").hide();
        $("#canvas").hide();
        $("#game-over-box").hide();

        $("#start-game-button").click(function () {
            $("#menu-page").hide();
            $("#game-over-box").hide();
            $("#canvas").show();

            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            var game = new Game(canvas, context);
            game.newGame();
            game.run();
        });
</script>

期望它能够正常工作。取而代之的是:

找不到变量:游戏

标签: javascriptjquery

解决方案


您的 Game 对象中不需要显式构造函数,因为您的 Game 已经是构造函数。只需删除构造函数并将所有需要的参数传递给 Game 构造函数本身:

let Game = function (canvas, context) {
    this.canvas = canvas;
    this.context = context;
}

Game.prototype.newGame = function () {
    //your code goes here
}

推荐阅读