Javascript 范围问题 [英] Javascript scope problem
问题描述
我正在调用这个函数,将结果分配给回调中的一个变量,然后记录结果,但我一直未定义.
I am calling this function, assigning the result to a variable in the callback and then logging the result, but I keep getting undefined.
var id;
test.getID(function(result) {
id=result;
});
console.log(id);
如果我将其更改为下面的代码,那么我可以看到记录的 id.
If I change it to the code below, then I can see the id logged.
var id;
test.getID(function(result) {
id=result;
console.log(id);
});
你知道我可以做什么才能访问 getID 函数的结果吗?
Do you know what I can do to be able to access the result of the getID function?
推荐答案
getID
函数需要调用其参数才能看到 id
更改.
The getID
function will need to invoke its parameter before you will see id
change.
由于您没有提供它的实现,让我们假设它是这样的.注意getID
的实现,它以一个函数为参数,f
,然后调用它.这是将设置 id
的时间.
Since you do not provide its implementation, let's assume it's something like this. Pay close attention to the implementation of getID
, it takes a function as the parameter, f
, and then invokes it. This is when id
will be set.
var id;
var test = {
getID: function(f){
var result = 666; //assume result comes from somewhere
f(result); //Note: this is where your function is getting invoked.
}
};
test.getID(function(result) {
id = result;
});
console.log(id); //prints 666
这篇关于Javascript 范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!