1. 程式人生 > 其它 >JavaScript-var-變數提升

JavaScript-var-變數提升

技術標籤:javascript

DATE 20201209 By WJB

變數提升就是作用域中宣告的變數在程式碼預編譯時會將所有的變數宣告語句提升到最前邊。

例如

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>lesson1</title>
    </head>
    <body>
    <script>    
      console.log(world);
    </script>
    </body>
</html>

執行結果:

執行時 提示world 未定義,其實在預編譯時就會報錯。

(1)對做如下修改

在console.log(world);語句下加一句“var world =“i like this world”;”

如下

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>lesson1</title>
    </head>
    <body>
    <script>    
      console.log(world);
      var world ="i like the world";
    </script>
    </body>
</html>

執行結果如下

執行結果顯示,world已經宣告但為定義。問題來了,為什麼log的時候world未宣告 而執行結果卻是顯示已宣告?

這裡就要提到“變數提升”了,varworld="iliketheworld"; 可以拆分為變數宣告和變數賦值。程式碼拆分為var world;world="iliketheworld";。

其中var world 被提到作用用於最前邊。編譯時程式碼如下

<script>    
   var world
   console.log(world);
   world ="i like the world";
</script>

這樣就可以解釋了執行結果了。

這樣就存在一個弊端,既所有的變數都會被宣告。如下例項

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>lesson1</title>
    </head>
    <body>
    <script>    
      if(false)
        { var world ="i like the world"; }
      console.log(world);
    </script>
    </body>
</html>

執行結果如下

很明顯world 宣告語句沒有被執行,但仍然被聲明瞭,這樣在就無形增加了編譯負擔。

變數提升增強了程式碼的容錯性,但增加了編譯和執行負擔,對最終的程式有不利影響。