[英]How can I use keyword 'this' in jQuery ajax success handle
我有一個這樣的課:
var MyClass = function(){
this.field = 'field';
}
MyClass.prototype.doSth(data){
//doSth with data and this.field;
}
MyClass.prototype.getData(){
$.ajax({
type: "post",
url: 'myurl',
}).success(this.doSth);
}
但是在doSth中,所有“ this”都指向jquery ajax對象而不是MyClass實例。
我添加了一個靜態文件_self
來指向MyClass
self MyClass._self = this;
那么所有的改變this
給MyClass._self
在doSth可以修復。 但是我認為這很丑。
我想知道在不修改doSth主體的情況下有什么方法可以解決我的問題嗎?
您可以使用context參數傳遞對象以在回調中使用。
$.ajax({
type: "post",
url: 'myurl',
context: this
}).success(function(d){
this.doSth(d);
});
我想你的意思是:
MyClass.prototype.getData = function(){
var self = this;
$.ajax({
type: "post",
url: 'myurl',
}).success(function(){
self.doSth();
});
};
“ getData”的定義需要一個如下所示的函數-您的版本沒有多大意義。
或者甚至可以使用jQuery.proxy(請參閱http://api.jquery.com/jQuery.proxy/ )
MyClass.prototype.getData = function(){
$.ajax({
type: "post",
url: 'myurl',
}).success( $.proxy(this.doSth, this) );
};
$ .proxy創建包裝函數,該包裝函數將在給定對象的上下文中調用封閉的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.