[英]Javascript function doesn't return anything
My javascript function doesn't return anything. 我的javascript函数未返回任何内容。 I really don't get it.
我真的不明白。 Is it a problem of variable scope?
这是可变范围的问题吗?
function getLanguage(){
navigator.globalization.getLocaleName(
function(locale){
var lan = locale.value;
},
function(){
var lan = null;
}
);
return lan;
}
Thank you! 谢谢!
This is a duplicate of the old asynchronicity problem , but there's a second issue as well -- scope. 这是旧异步问题的复制品,但是还有第二个问题-范围。
First of all, scope. 首先,范围。 The
lan
variable is defined inside the internal function, and so cannot be seen from outside. lan
变量在内部函数中定义,因此无法从外部看到。
function getLanguage(){
var lan;
navigator.globalization.getLocaleName(
function(locale){
lan = locale.value;
},
function(){
lan = null;
}
);
return lan;
}
That was easy. 那很简单。 But it still won't work, due to asynchronity.
但是由于异步,它仍然不起作用。 You have to set up your function to use a callback instead:
您必须将函数设置为使用回调:
function getLanguage(callback){
navigator.globalization.getLocaleName(
function(locale){
callback(locale.value);
},
function(){
callback(null);
}
);
}
Also, by now, we don't even need the variable, so i got rid of it. 而且,到目前为止,我们甚至不需要该变量,所以我摆脱了它。
Then, you call it as: 然后,将其称为:
getLanguage(function(lan){
// something with lan here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.