繁体   English   中英

从JavaScript中的函数参数返回值

[英]Return value from function parameter in Javascript

我正在尝试使用Fingerprintjs2 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

我猜这与作用域有关,所以有什么办法可以在外部作用域中设置变量,还是我需要将以下所有代码放入此函数调用中?

我已经阅读了有关获取嵌套函数的值的其他问题,但在这种情况下似乎没有任何作用。

这将不起作用,因为您正在返回异步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);
});

这不是你应该做的方式。 我正在使用ES6编写代码。

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

您无法在函数外部调用var,请了解是否通过对象或字符串将其发送出去。 document.write(Fingerprint2Obj.output);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM