2017-07-27 151 views
1

我已經讀了很多關於關閉和我經常使用它們然而我發現我不明白的情況下。 爲什麼我的函數不能通過測試訪問hello變量?它不應該通過範圍更改來找到它嗎? 我的代碼:帶來了全新的功能分爲封閉

(function($){ 
    var hello="hello world" 
    $.test=function(a){ 
     alert(hello+" 1") 
     a()} 
})(this) 
test(function(){alert(hello+" 2")}) 
+2

你似乎什麼期望是*動態範圍*(從調用者繼承),但JavaScript有*詞法範圍*(繼承書面)。 – deceze

+0

請不要在標題中添加「解決」,在回答綠色的復指出,你找到了一個解決方案 –

+0

對不起,我使用屏幕閱讀器,不知道 – user7951676

回答

6

JavaScript使用lexical scope帽尖到deceze)。範圍由函數所在的位置定義而不是由它傳遞的位置或從哪裏調用。

如果你想有一個函數來訪問數據,從它傳遞給作用域的變量,你需要因此它需要一個參數來定義它,然後你需要傳遞的數據。

"use strict"; 
 
(function($) { 
 
    var hello = "hello world" 
 
    $.test = function(a) { 
 
    alert(hello + " 1") 
 
    a(hello); 
 
    } 
 
})(this); 
 
test(function(passed_data) { 
 
    alert(passed_data + " 2") 
 
});

這是一種常見的設計圖案。例如參見the Promise API

myFirstPromise.then((successMessage) => { 
    // successMessage is whatever we passed in the resolve(...) function above. 
    // It doesn't have to be a string, but if it is only a succeed message, it probably will be. 
    console.log("Yay! " + successMessage); 
}); 

注意傳遞給then()功能是如何發生提供它去上班的數據參數。

+0

謝謝你,我會接受,但它說我得體重5分鐘 – user7951676