简体   繁体   中英

Return value from function parameter in Javascript

I'm trying to use the fingerprintjs2 javascript library, to get browser fingerprints.

The following code works ok:

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

However, I would like to set a variable outside of this block, to be used later eg:

var output;

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

document.write(output);

but in this case I get the output:

undefined

I'm guessing this is related to scope, so is there any way to set the variable in the outer scope, or do I need to put all following code inside this function call?

I've read other questions about getting the value of nested functions, but none seem to work in this case.

this will not work because you are printing the output before the asynchronous get has returned.

try this:

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);
});

it is not the way u should do it. i"m writeing the code using ES6.

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

you can't call the var outside the function, instand if you send it out via object or string. document.write(Fingerprint2Obj.output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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