2016-08-16 150 views
0

我試圖使用fingerprintjs2 javascript庫來獲取瀏​​覽器指紋。Javascript中函數參數的返回值

下面的代碼工作正常:

new Fingerprint2().get(function (result) { 
    var output = result; 
    document.write(output); 
}); 

不過,我想設置此塊的變量外,稍後用於例如:

var output; 

new Fingerprint2().get(function (result) { 
    output = result; 
}); 

document.write(output); 

但在這種情況下,我得到輸出:

undefined 

我猜這是與範圍有關,所以有什麼辦法來設置變量在t他外部的範圍,還是我需要把這個函數調用內的所有以下代碼?

我讀過關於獲取嵌套函數的值的其他問題,但在這種情況下似乎沒有任何工作。

+0

「與範圍有關」 - 不,這是因爲在執行'output = result;'之前調用'document.write(output);' – Igor

+0

它是未定義的,因爲'document.write(output);'回調 –

+0

get調用異步運行,所以''.get()'調用仍在運行時調用'document.write(output)'。 – theClap

回答

0

這將不起作用,因爲您在異步get返回之前正在打印輸出。

試試這個:

var output; 

var callbackFunction = function(result) { 
output = result; 
document.write(output); 
//do whatever you want to do with output inside this function or call another function inside this function. 
} 

new Fingerprint2().get(function (result) { 
    // you don't know when this will return because its async so you have to code what to do with the variable after it returns; 
    callbackFunction(result); 
}); 
+0

這與我給出的第一個示例類似 - 其中document.write工作,但我希望輸出變量在外部作用域中可用,並在可能的情況下由其他函數使用。 – finoutlook

+0

這正是OP的文章中所寫的內容... – theClap

+0

那麼你不能。該代碼是異步的,所以你需要包裝它。你可以做的是附加回調函數,並在該函數內部做異步塊 –

0

它不是ü應該做到這一點。 。 我「米writeing使用ES6代碼

let Fingerprint2Obj = new Fingerprint2().get(function (result) { 
    let obj = { 
    output: result 
    } 
    return obj; 
}); 

你不能調用函數外的變種,instand如果通過對象或字符串發送出去 文件撰寫(Fingerprint2Obj.output);

+1

嗡嗡聲我不認爲'Fingerprint2Obj'將採用回調返回的值 –

+0

這不能解決OP想要從全局變量中返回異步調用返回的值的問題調用。 – theClap