What does “this” refer to in the following javascr

2019-08-11 03:40发布

问题:

DISCLAIMER: I am asking about a specific use of this, not what this is used for in general. So, please no google/copy/paste speed answers (:

I have the javascript/jquery code below:

var req = {};

function getData()
{
    var fromPage = 0;
    var toPage = 1;

    req = $.ajax({
                    url: "/_vti_bin/lists.asmx",
                    type: "POST",
                    dataType: "xml",
                    data: xmlData,
                    complete: onSuccess,
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error: " + xhr.statusText);
                        alert(thrownError);
                    },
                    contentType: "text/xml; charset=\"utf-8\""
                });

     req.fromPage = fromPage;
     req.toPage = toPage;
}

function onSuccess(resp) {
    alert(this.fromPage);
}

I find it pretty confusing that the code is using fromPage in two places (sorry not my code).

Does this refer to the var declared inside of getData or the one that is part of the req object? Or maybe something else entirely....

Any help appreciated.

回答1:

According to jQuery.ajax documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

In other words, since you didn't set the context option, this will be the options object {...} passed as the parameter to $.ajax.

The code you posted seems wrong: it reads fromPage from the wrong object. It would work if you set fromPage on the options object instead:

req = $.ajax({
    //other options here...
    fromPage: fromPage
});


回答2:

onSuccess() is being called from the complete handler in the context of the ajax request, which is being assigned to the req object, so this is that context - i.e. the req object, and fromPage is in fact req.fromPage



回答3:

I belive this is refering to req.fromPage since that is the object that contains the called function.