JN0*_*zze 7 javascript ajax jquery this
我在javascript中的对象编程有一点问题
有一个"类"任务,它有几个方法,一个包含在JQuery($.ajax)的帮助下异步发送请求的方法.请求成功后,必须执行类Task的特定方法(例如successFunction).
问题是,在successFunction的主体中查询之后,使用关键字引用类是不可能的this,因为上下文已经改变,并且它包含对执行ajax请求的jquery-object的引用.
有哪些变体引用函数内部的当前Task对象,这些对象不是直接引起的,而是外部存在的?(例如,通过事件或ajax)
Dar*_*rov 10
通常在AJAX事件(例如成功回调)中,this引用$.ajax调用返回的对象.您可以使用该context参数更改成功回调中的上下文:
$.ajax({
url: '/foo',
context: this, // <!-- change the context of the success callback
success: function(result) {
// 'this' here will refer to whatever it refered outside
}
});
Run Code Online (Sandbox Code Playgroud)
您还可以传递复杂对象:
$.ajax({
url: '/foo',
context: { element: this, foo: 'bar' },
success: function(result) {
// you can use 'this.element' and 'this.foo' here
}
});
Run Code Online (Sandbox Code Playgroud)
您可以定义一个包含对象引用的变量:
function Task() {
var that = this;
this.call = function() {
$.ajax({
url: '/foo',
success: function(result) {
console.log(that); // <-- you cann access this object via that
}
});
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256 次 |
| 最近记录: |