什么是“这个"?参考下面的javascript? [英] What does "this" refer to in the following javascript?
问题描述
免责声明:我要问的是this
的特定用途,而不是this
的一般用途.因此,请没有google/copy/paste速度答案(:
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 (:
我下面有javascript/jquery代码:
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);
}
我发现代码在两个地方使用fromPage
令人感到困惑(对不起,不是我的代码).
I find it pretty confusing that the code is using fromPage
in two places (sorry not my code).
this
是引用在getData
内部声明的var还是作为req
对象一部分的var?或也许完全是其他东西....
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....
任何帮助表示赞赏.
推荐答案
根据 jQuery.ajax
文档:
According to jQuery.ajax
documentation:
所有回调中的此引用是上下文选项中传递给设置中$ .ajax的对象;如果未指定上下文,则是对Ajax设置本身的引用.
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.
换句话说,由于您没有设置context
选项,因此this
将是作为参数传递给$.ajax
的选项对象{...}
.
In other words, since you didn't set the context
option, this
will be the options object {...}
passed as the parameter to $.ajax
.
您发布的代码似乎是错误的:它从错误的对象读取fromPage
.如果在options对象上设置fromPage
,它将起作用:
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
});
这篇关于什么是“这个"?参考下面的javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!