开发者

jQuery Deferred Ajax, JavaScript scope issue?

I thought this would be pretty straight forward, but it's not working (live example at http://jsfiddle.net/QtjaG/):

$.resx = function() {
    var result = this;

    return $.get("/", function() {
        result = "yo";
    });
};

var labels;

$.resx.call(labels).then(function() {
    console.log(labels);
});

Since $.resx.cal开发者_开发百科l(labels) should set the this context within $.resx() to labels, shouldn't console.log(labels) log yo?


In the function (the "$.resx" function), you do set "result" to refer to the same thing that "labels" refers to. However, in the callback from "$.get()" you then set it to "yo". That string constant "yo" is a different value than "labels", which was actually not initialized to anything in the first place. There's no way in JavaScript to have a reference to a reference; if "labels" had been defined to have some value:

var labels = "this is a string";

then "result" would end up being another reference to that string. However, strings are immutable, so from inside the "$.get()" success handler you can't change that string.

Try this:

$.resx = function() {
    var result = this;

    return $.get("/", function() {
        result[0] = "yo";
    });
};

var labels = ["not yo"];

$.resx.call(labels).then(function() {
    console.log(labels[0]);
});


If you console.log(this), you get window. That's because your function's scope is global. I think what you're looking for is the "apply" method: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply. However I don't think you need it because you can do the following simply below. The callBack function's closure will wrap around the "labels" reference. And because functions are first-class objects, you can pass them in directly as delegates and call them like callBack(x);

$.resx = function(callBack) {      
    return $.get("/", function() {       
        callBack("yo");
    });  
};

var labels;

$.resx(function(response){
    labels = response;  
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜