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()
功能是如何發生提供它去上班的數據參數。
你似乎什麼期望是*動態範圍*(從調用者繼承),但JavaScript有*詞法範圍*(繼承書面)。 – deceze
請不要在標題中添加「解決」,在回答綠色的復指出,你找到了一個解決方案 –
對不起,我使用屏幕閱讀器,不知道 – user7951676