2016-09-29 76 views
3

我试图将fingerprint2结果存储在var中。如何将fingerprint2结果存储在var中

var info = {}; 
new Fingerprint2().get(function(result, components){ 
    info.fingerprint = result; 
}); 
alert(info.fingerprint); 

但不起作用 是有像一个更好的办法:

var fp = new Fingerprint2().get(); 

或一些增强的方法是什么?

编辑: 现代&灵活的浏览器指纹库,继承了原fingerprintjs http://valve.github.io/fingerprintjs2/

用法:

new Fingerprint2().get(function(result, components){ 
    console.log(result); //a hash, representing your device fingerprint 
    console.log(components); // an array of FP components 
}); 

回答

5

不工作按照预期的代码,因为Fingerprint2().get(...)是异步的 - 这意味着alert(info.fingerprint)将在之前运行回调函数传递给get已完成。

要理解为什么这是必要的,如果你不明白异步的概念,请看demo page。你会看到它说明计算指纹需要多长时间。您alert将在get被调用和计算完成之间运行,因此无法知道指纹会是什么。

在回调函数期间,唯一可以保证指纹的是指纹。

var info = {}; 

new Fingerprint2().get(function(result, components) { 
    info.fingerprint = result; 

    afterFingerprintIsCalculated(); 
}); 

function afterFingerprintIsCalculated() { 
    alert(info.fingerprint); 
} 



// BETTER (no global state) 
new Fingerprint2().get(function(result, components) { 
    var info = { 
     fingerprint: result 
    }; 

    processFingerprint(info); 
}); 

function processFingerprint(data) { 
    alert(data.fingerprint); 
} 
+0

alert()是我的代码中的示例,我想将它存储在var中,在我的JavaScript代码中使用它。如何将其存储在var secure中 –

+1

同样的规则适用 - 可以在变量中使用它,但*只能在get内部的函数运行后使用。查看顶部示例 - 从'afterFingerprintIsCalculated'内的info变量读取是安全的 - 因此您可以将需要从其中读取的代码放在那里。 – iblamefish

+0

有没有一种方法来存储它并使用副功能?我的代码不应该在这个函数中运行,因为我有一些其他变量@iblamefish –

相关问题