他們沒有什麼不同變量,它是同一個變量...但你有沒有在函數結束時,你return
之前分配一個值myVariable
。
這裏的正確模式是getVariable
和asychronousFunction
接受回調,當asynchronousFunction
完成執行時會執行回調。
function getVariable(callback) {
var myVariable;
asyncronousFunction(function(/* pass callback as one of the parameters */){
myVariable = ...
});
// Don't return myVariable, as it's useless at this point
};
function asyncronousFunction(callback) {
// This simulates the asynchronous call. When the call finishes, invoke callback and pass the result as a parameter.
setTimeout(function() {
callback("result");
}, 1000);
}
您應該然後編輯你如何使用功能getVariable()
。
那麼,你可能有:
var value = getVariable();
// do whatever with value
value++;
你現在應該有:
getVariable(function (value) { // value is now passed as a parameter
value++;
});