javascript - 使用 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>
期望它能够正常工作。取而代之的是:
找不到变量:游戏
解决方案
您的 Game 对象中不需要显式构造函数,因为您的 Game 已经是构造函数。只需删除构造函数并将所有需要的参数传递给 Game 构造函数本身:
let Game = function (canvas, context) {
this.canvas = canvas;
this.context = context;
}
Game.prototype.newGame = function () {
//your code goes here
}
推荐阅读
- vue.js - 嵌套数组 Vue 中的总计
- python - 如何在soup.find_all中打印“未找到”?
- python - 将数据保存在 JSON 文件中
- discord - Discord Bot (JDA) 没有修改我的角色
- javascript - 使用 jshjohnson 选项按文本选择项目
- powerbi - Power BI:如何更改矩阵中特定行的背景颜色?
- javascript - 如何在 React 中使用 API 数据
- java - 如果我将注解@Component 放在接口或实现类上,有什么区别?
- leaflet - 使用 Leaftejs 和 vuejs 进行图层控制
- javascript - Nuxt.js 无法动态编译模板