Consider the following example of using jQuery’s (v1.8.3) ajax() method while attempting to supply a context.
for(var i=0; i<3; i++) {
$.ajax({
url: "foo",
context: i,
success: function() { console.log(this); }
}
Expected output would be 3 Number objects, representing 0, 1 and 2 (not necessarily in that order.) In fact, the output to console is 2 Number objects, and 1 Object object, containing ajax request data.
> Number
> Object {url: "foo", isLocal: false, global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8"…}
> Number
Why do I not receive 3 Number objects?
After a bit of digging in the jQuery v1.8.3 source, I found this:
This means whenever the
contextoption of anajax()call is falsy, the value assigned to the callback as thethiscontext parameter is an object returned byjQuery.ajaxSetup().Be aware that passing any falsy value as a
contextoption will result in this behaviour, including0,nulland"".I beleive a small change could remove this ambiguity, and I would lodge a ticket with the jQuery development team, however I don’t know if they’ll appreciate a backwards incompatible change that breaks half the internet 🙁