为什么';我的函数有Javascript变量的作用域吗?

为什么';我的函数有Javascript变量的作用域吗?,javascript,Javascript,我正试着让我的头脑重新思考一些问题 我已经通过 这些函数可以通过 场景B调用一个函数startGame(),该函数本身调用传递了total的increment函数,但这不起作用 这与此无关 为什么它会失去total的范围 因为您已更改了增量函数。您不再递增全局total变量,而是递增声明为参数的局部tot变量。确切的错误是什么?tot+=1只递增局部变量。它对总数没有影响。实际上,javascript中没有传递引用-请参阅:可能重复的 <body> <script sr

我正试着让我的头脑重新思考一些问题

我已经通过

这些函数可以通过

场景B调用一个函数
startGame()
,该函数本身调用传递了total的increment函数,但这不起作用

这与此无关

为什么它会失去total的范围


因为您已更改了
增量
函数。您不再递增全局
total
变量,而是递增声明为参数的局部
tot
变量。

确切的错误是什么?
tot+=1
只递增局部变量。它对
总数没有影响
。实际上,javascript中没有传递引用-请参阅:可能重复的
<body>
    <script src="app.js" type="text/javascript"></script>
    <button onclick="increment();"></button>
     <h2 id="number"></h2>
</body>
let total = 0;

function increment() {
    total += 1;
    document.getElementById('number').innerHTML = total;
}

setTimeout(() => {
  console.log('total is: ', total);
}, 5000)
    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)