2016-07-15 74 views
-1
new SomeClass().get(function(resultvariable){ 
    console.log(resultvariable); // works 
}); 

在類函數之外如何使用「resultvariable」?在類之外使用javascript變量functuon

+0

is'.get' async? –

+1

http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –

回答

1

在類之外聲明一個全局變量。然後將resultvariable的值分配給該全局變量。

var globalVariable; 
new SomeClass().get(function(resultvariable){ 
    console.log(resultvariable); // works 
    globalVariable = resultvariable; 
}); 
+0

這通常不會工作。函數的名稱和回調參數的方式非常強烈意味着它是異步的。大多數時候,全球範圍內不會有足夠的價值來實現目標。 – Quentin

+0

即使它是異步的,它也會被賦值,而不是在'.get()'後面調用。 – Eddi

+0

......這就是我所說的。 – Quentin