0

I have a JSON object that is returned inside a function (see below) and that in turn is inside a parent function and then a global function. There is a further child function within that global function that needs access to the JSON to parse the records.

I have left out some things that are not really part of the problem but hopefully included enough to explain the problem I have! You can see that

MyFunc.prototype.CreateMine = function(){
//do some work...
    submit: function(e,v,m,f){
        var xhr = new jsonRequest()
        xhr.onreadystatechange = function(){
            var jsonText = JSON.parse(xhr.responseText); //jsonText now contains my data
        };
    }
//need to access jsonText...
    }
}

Let me know if the example of not complete enough, thanks in advance Chris

4

1 回答 1

0

或许您应该了解更多关于JavaScript 中作用域的工作原理。简单来说,在外部函数中创建的所有变量都在内部函数中可用。所以你只需要jsonText在“上层”函数之一中声明你的。

var注意in的缺失submit:这样它将尝试jsonText在作用域树中查找变量 upper:

MyFunc.prototype.CreateMine = function(){
    var jsonText
    //do some work...
    submit: function(e,v,m,f){
        var xhr = new jsonRequest()
        xhr.onreadystatechange = function(){
            jsonText = JSON.parse(xhr.responseText); //jsonText now contains my data
        };
    }
    jsonText // available
    }
}

但是,在您的情况下,回调延迟会更好,因为 insubmit jsonText是异步更改的,因此您无法在调用submit.

function myCallback(myData) {
    // do smt with your data
}
MyFunc.prototype.CreateMine = function(){
    //do some work...
    submit: function(e,v,m,f){
        var xhr = new jsonRequest()
        xhr.onreadystatechange = function(){
            var jsonText = JSON.parse(xhr.responseText);
            myCallback(jsonText)
        };
    }
    }
}
于 2012-08-21T13:30:21.347 回答