“这个”是什么意思?参考下面的javascript?
免责声明:我问的是 this
的具体用途,而不是 this
的一般用途。因此,请不要使用 google/copy/paste 速度答案(:
我有下面的 javascript/jquery 代码:
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
非常令人困惑(抱歉不是我的代码)。
this
是指在 getData
中声明的 var 还是作为 req
对象一部分的变量?或者可能完全是其他东西...... 。
任何帮助表示赞赏
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据
jQuery.ajax
文档:换句话说,由于您没有设置
context
选项,因此this
将是作为参数传递的选项对象{...}
到$.ajax
。您发布的代码似乎是错误的:它从错误的对象读取
fromPage
。如果您在选项对象上设置fromPage
,它就会起作用:According to
jQuery.ajax
documentation: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 setfromPage
on the options object instead:onSuccess()
正在 ajax 请求上下文中的complete
处理程序中调用,该处理程序被分配给req
对象,因此 < code>this 是上下文 - 即req
对象,而 fromPage 实际上是req.fromPage
onSuccess()
is being called from thecomplete
handler in the context of the ajax request, which is being assigned to thereq
object, sothis
is that context - i.e. thereq
object, and fromPage is in factreq.fromPage
我相信
this
指的是req.fromPage
因为它是包含被调用函数的对象。I belive
this
is refering toreq.fromPage
since that is the object that contains the called function.