変数が別の関数 (およびおそらく別のスコープ) から取得された場合、コールバックを渡して、2 番目の関数がコールバックを実行するときに変数を提供できます。いつ存在するかを待つ必要はありませんが、2 番目のスクリプトがそれを提供するまで待つ必要があります。
//in the second script:
var varIWant = 'foo'
function fromSecondScript(callback){
callback(varIWant);
}
//in the first script:
function fromFirstScript(){
fromSecondScript(function(theVar){
//"theVar" in this function scope is "varIWant" from the other scope
})
}
これを行う別の方法は、事前に定義されたローダー スクリプトを使用して、コールバックを集約し、変数が設定されたらそれらを呼び出すことです。
var aggregator = (function(){
var stored = {};
return {
//adds a callback to storage
addCallback : function(varName,callback){
if(!stored.hasOwnProperty(varName)){
stored[varName] = [];
}
stored[varName].push(callback);
},
//executes stored callbacks providing them data
execute : function(varName,data){
if(stored.hasOwnProperty(varName)){
for(var i=0;i<stored[varName].length;i++){
stored[varName][i](data)
}
}
}
}());
//in the first script add callbacks. you can add any number of callbacks
aggregator.addCallback('VarExists',function(theVar){
//do what you want when it exists
});
aggregator.addCallback('VarExists',function(theVar){
//another callback to execute when var exists
});
//in the second script, execute the callbacks of the given name
aggregator.execute('VarExists',theVarYouWantToShare);