我想在浏览器控制台中引用const game
,但它高喊game
尚未定义,但实际上没有定义。我也不能引用我声明的任何const。
我尝试使用let
甚至var
,但问题仍然存在。这是我在online.js
中声明的index.html
文件
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Multiply</title>
<link rel="stylesheet" href="style.css">
<link rel="manifest" href="manifest.json">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
</head>
<body>
<div id="ver">version</div>
<div class="wraper">
<div class="submit">
<button type="submit" id="level">hard</button>
</div>
<div class="numbers" id="numbers">div</div>
<div class="answer">
<input type="tel" id="answer">
</div>
<div class="submit">
<button type="submit" id="submit">Sprawdź!</button>
</div>
</div>
<!-- <script src="main.js"></script> -->
<script type="module" src="online.js"></script>
</body>
</html>
import Game from '/Game.js';
const numbers = document.getElementById("numbers");
const answer = document.getElementById("answer");
const button = document.getElementById("submit");
const level = document.getElementById("level");
const ver = document.getElementById("ver");
const game = new Game();
window.addEventListener('load', () => {
game.pair.flag = true;
numbers.innerText = game.writeNumbers();
answer.focus();
})
button.addEventListener('click', () => {
game.checkAnswer(answer.value);
console.log(game.numbers);
numbers.innerText = game.writeNumbers();
})
那么为什么.addEventListener
可以引用该const但我不能呢?
答案 0 :(得分:3)
默认情况下,在模块顶层声明的变量不会隐式分配给全局对象。 (这可以说是一件好事-作用域控制有助于保持代码的可维护性。)如果要在模块内部的控制台中创建可引用的全局变量,则必须明确地做到这一点:
gcloud config get-value project
(但是您可能仅出于调试目的而执行此操作-可能,一旦脚本按需工作,最好将window.game = new Game();
的作用域再次分配给模块,并用game
进行声明)>