問題 - 如何將變量傳遞給全局範圍? :如何將變量傳遞給全局範圍
var global_variable;
chrome.storage.local.get('ABC',function(result){
global_variable = result; //pass result to global var.
});
console.log(global_variable); //outputs undefined, why!!!?
問題 - 如何將變量傳遞給全局範圍? :如何將變量傳遞給全局範圍
var global_variable;
chrome.storage.local.get('ABC',function(result){
global_variable = result; //pass result to global var.
});
console.log(global_variable); //outputs undefined, why!!!?
你設置一個異步回調函數裏面的變量。回調在獲取操作完成後運行。
您的代碼將在這個順序執行:
chrome.storage.local.get("ABC",callback);
然後
console.log();
然後
callback()
您可以驗證通過把一個的console.log語句進行回調看到它在當前之後運行。
Javascript函數在運行任何異步回調調用之前運行完成。
這樣做可能更有意義,就像你現在所擁有的一樣。
//define the callback
function callbackFunction(result){
global_variable = result; //pass result to global var.
}
//run the get. When it is complete the callback will be added to a queue
//to run next after current operations have completed
chrome.storage.local.get('ABC',callback);
// this will run immediately after the get call
console.log(global_variable);
如果你想與您的變量工作,你將不得不把邏輯的回調(或由回調稱爲一個單獨的函數。
這只是因爲'ABC',function(result){
設置的全局變量之前console.log()
啓動。
因爲chrome.storage.local.get
是異步啓動的。
要verifiy它,測試該代碼:
var global_variable;
chrome.storage.local.get('ABC',function(result){
global_variable = result; //pass result to global var.
test();
});
function test() {
console.log(global_variable);
}
我猜想,不知道返回了什麼'result'的值是,你希望將一個值傳遞給一個未定義的變量的全局範圍,下面的回調變化都將定義一個全局範圍的新變量,並將'results'的值賦給它請記住,該範圍與窗口對象內的層次結構有關,而不是腳本。
function callbackFunction(result){
window.global_variable = result;
}
console.log(global_variable);
您也可以動態注入腳本標記,其中src屬性是您的全局值。
function callbackFunction(result){
var js = document.createElement('script');
js.src = 'var global_variable = ' + result + ';';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
}
雖然我覺得這似乎爲實現相同的結果有點冗長。
該函數被稱爲「異步」。 – 2013-04-06 14:17:18
我曾經寫過[外行人對你遇到的問題的解釋](http://stackoverflow.com/a/11689804/938089?after-calling-chrome-tabs-query-the-results-are-not - 可選)。它遵循與你的代碼相同的結構,所以它應該很容易快速跳入。 – 2013-04-06 14:26:06
我可能會注意到,這些解決方案都不符合OP所要求的......這就是將變量「移動」到全局範圍。所有這些答案只爲全局範圍內的另一個變量賦值,並且不將原始變量移動到全局範圍... jus say'n;) – Epiphany 2015-02-08 02:03:43