我在使用'this'關鍵字時遇到了一些問題。我明白爲什麼下面不工作,但無法弄清楚如何解決它......使用原型模式在ajax回調中訪問'this'
//Namespace
var CPT = CPT || {};
//Constructor
CPT.Grid = function (hostElement, surlWeb) {
this.hostElement = hostElement;
this.surlWeb = surlWeb;
}
//Prototype
CPT.Grid.prototype = {
init: function() {
$.ajax({
url: this.surlWeb,
headers: { "accept": "application/json" },
success: this.showItems
});
},
showItems: function (data) {
//do some work
// this is the error... no access to hostElement because 'this' is the AJAX call
this.hostElement.html(items.join(''));
}
}
function getProducts() {
var grid = new CPT.Grid($("#displayDiv"), someUrl);
grid.init();
}
我知道我可以沒有一個獨立的showItems功能可能解決這個問題,但我想看看如何做另一種方式。理想情況下,我想將當前對象的引用傳遞給成功處理程序,但無法弄清楚如何做到這一點...
在進入ajax調用之前,您可以簡單地將'this'賦值給其他變量,然後在該變量上調用您的方法。常見的方法是'var self = this; self.my_method_name'。或者您可以使用'.ajax()'調用的上下文字段並傳遞'this' –