0

我在使用 javascript 函数回调时遇到问题。

例如我有这样的代码:

var BASE = {

    // Constructor of the class
    createNew: function(name) {
        var base = {};

        base.ajax = function(callback, url) {
            // Create XMLHTTPRequest object
            var httpRequest;
            if (window.XMLHttpRequest) {
                httpRequest = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }

            httpRequest.onreadystatechange = function() {
                // Check status of our request
                // this is called on every state change
                if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                    // call the callback function
                    callback.call(httpRequest.responseText);
                }
            };

            httpRequest.open("GET", some_url, true);
            httpRequest.send();
        };


        return base;
    }
};

然后创建一个继承BASE的类:

var Test = {

    createNew: function() {

        var test = BASE.createNew();

        test.json = {};

        test.ajax( function(){
            test.json = JSON.parse( this );
        });

        return test;
    }
};

然后我创建了另一个类 myTest,它继承了 Test:

// create class for 300x250    
var myTest = {
    createNew: function() {
        var mytest = Test.createNew();
        return mytest;
    }
};

var mytest = myTest.createNew();

console.log(mytest.json);

但是,当我尝试 console.log(mytest.json) 时,我无法获取数据。我知道这是因为在 Test 类中,json 在 ajax 函数中,但我不知道如何解决这个异步问题,知道吗?

4

0 回答 0