2016-08-16 149 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