簡體   English   中英

為什么我的函數沒有Javascript變量的范圍?

[英]Why Doesn't My Function Have Scope Of The Javascript Variables?

我正在努力使自己了解有關范圍/披露的內容。

我已經設置了一個index.html,其中有一個通過<script>插入的app.js

這些功能可以通過<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)

方案B調用了一個函數startGame() ,該函數本身調用帶有傳入的total的增量函數,但這不起作用。

這與它無關。

為什么會失去總數的范圍?

因為您已經更改了increment功能。 您不再增加全局total變量,而是增加了聲明為參數的局部tot變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM