我试图了解范围/闭包。
我已经通过<script>
可以使用<button onclick="increment();>"...
的index.html
<body>
<script src="app.js" type="text/javascript"></script>
<button onclick="increment();"></button>
<h2 id="number"></h2>
</body>
app.js
let total = 0;
function increment() {
total += 1;
document.getElementById('number').innerHTML = total;
}
setTimeout(() => {
console.log('total is: ', total);
}, 5000)
因此,上面的场景A有一个函数,当在html中调用时,增加let total...
罚款。然后它将它发布在h2标签/ html中。这很好用。
并且超时是为了测试5秒后,它确实是let total...
变量已经增加(我想知道如果我在函数中创建一个全局变量)。
场景B调用一个函数(startGame()
,其中本身调用增量函数并传入总数)但此不会工作。为什么会失去总数?
app.js
let total = 0;
function startGame() {
console.log('game has started');
increment(total);
console.log('game has finished');
}
function increment(tot) {
tot += 1;
document.getElementById('number').innerHTML = tot;
}
setTimeout(() => {
console.log('total is: ', total);
}, 5000)
答案 0 :(得分:0)
场景B调用一个函数
startGame()
,它本身调用增量函数并传入总数,但这不起作用。
这与它无关。
为什么会失去总数?
因为您已更改了increment
功能。您不再递增全局total
变量,而是递增声明为参数的本地tot
变量。