Javascript scope problem

青春壹個敷衍的年華 提交于 2019-12-12 21:23:18

问题


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

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

Do you know what I can do to be able to access the result of the getID function?


回答1:


The getID function will need to invoke its parameter before you will see id change.

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



回答2:


A closure would work for you as well:

var id,
test = {
  getID: function (id) {
    this.id = id;
  },
  id: -1
};

test.getID((function(result) {
    id=result;
    return id;
})(78));
console.log(id);


来源:https://stackoverflow.com/questions/7167261/javascript-scope-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!