internet explorer 9 & javascript variable scoping

2019-08-07 07:44发布

问题:

this code works in Chrome & Firefox but not in IE9 ... need some hints ...

var obj = {
    data: [],

    json: function() {
        var self = this;
        $.getJSON("highscore.json", function(resp) {
            self.data = resp.splice(0);
        });
    }
};

Update:

thx for your help ...

it was an issue from the ie9, ie has thrown the error code "c00ce56e" - it's an issue with charset. i'll try another header in the php scripts ...

thx @ all

回答1:

Your code looks fine to me, other than that data won't be populated until the json request is done, which is NOT instant because ajax is asynchronous.

obj.json();
alert(obj.data); // []
setTimeout(function(){
    alert(obj.data); // ["foo","bar","foobar"]
},5000);

Update
I suggest adding a property to your object called request, and store the $.getJSON request in it. At that point it doesn't make sense to store the data directly on the object because you can always get it from the request.

var obj = {
    request: {done:$.noop,fail:$.noop,always:$.noop},

    json: function() {
        this.request = $.getJSON("highscore.json");
    }
};
obj.json();
// you can run the following as many times as you need to use the data.
obj.request.done(function(data){
    alert(data.splice(0));
});

just note that in it's current form you must call .json() before you can add callbacks to the request.