为什么我的函数不具有Javascript变量的范围?

时间:2018-04-18 08:47:10

标签: javascript

我试图了解范围/闭包。

我已经通过<script>

设置了一个带有app.js的index.html

可以使用<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)

1 个答案:

答案 0 :(得分:0)

  

场景B调用一个函数startGame(),它本身调用增量函数并传入总数,但这不起作用。

这与它无关。

  

为什么会失去总数?

因为您已更改了increment功能。您不再递增全局total变量,而是递增声明为参数的本地tot变量。