1. 程式人生 > 其它 >7.函式作用域和全域性汙染

7.函式作用域和全域性汙染

技術標籤:JavaScript

下面,我們直接貼程式碼,首先,在js資料夾下新建一個first.jsp檔案,如下:

const name = "Mike";
function temp() {
    console.log("Hello, I'm "+name);
}

然後新建一個second.jsp檔案,如下:

const name = "John";
function temp() {
    console.log("Hello, I'm "+name);
}

之後我們在JavaScript資料夾下新建一個07_global.html檔案,如下:

<!DOCTYPE html>
<html lang="UTF8">
<head>
    <meta charset="UTF-8">
    <title>全域性汙染</title>
</head>
<body>
    <script type="text/javascript" src="js/first.js"></script>
    <script type="text/javascript"
src="js/second.js">
</script> <script type="text/javascript"> hello(); </script> </body> </html>

此時的執行結果為:
在這裡插入圖片描述
很明顯,他只認第一個索引到的hello函式,並且顯示name已經被定義了,這就是所謂的全域性汙染。
那麼,我們該怎麼解決這個問題呢,很簡單,看下邊:
修改first.jsp檔案如下:

(function () {
    const name = "Mike"
; function hello() { console.log("Hello, I'm "+name); } window.first = hello(); })();

而second.jsp檔案修改如下:

(function () {
    const name = "John";
    function hello() {
        console.log("Hello, I'm "+name);
    }
    window.second = hello();
})();

window是全域性變數,如此設定猴,我們就可以順利呼叫兩個同名的方法,且不讓其中的方法和變數因為重名而產生全域性汙染啦!!!!
這裡,我們修改07_global.html檔案如下:

<!DOCTYPE html>
<html lang="UTF8">
<head>
    <meta charset="UTF-8">
    <title>全域性汙染</title>
</head>
<body>
    <script type="text/javascript" src="js/first.js"></script>
    <script type="text/javascript" src="js/second.js"></script>

    <script type="text/javascript">
        first();
        second();
    </script>
</body>
</html>

此時的執行結果為:
在這裡插入圖片描述
成功啦!!!!驚不驚喜,意不意外!!!