我想知道是否有一种优雅的方式来执行以下代码,而不必首先调用父对象“that”。如果我尝试在ajax请求中使用“this”,它显然会引用Ajax对象。
至少我认为这意味着什么。
var ObjectA = Class.create();
ObjectA.prototype = {
initialize: function() {
//Workaround I use
that = this;
},
getData: function(bounds) {
//ajax to get some data
url = "http://www.data.com/";
new Ajax.Request(url, {
method: 'get',
onSuccess: function(response) {
// Handle the response content...
that.workData(response.responseText);
//THIS IS MY DOUBT.
//How do I access the parent object without having to previously calling it "that" first?
}
});
},
workData: function(data){
//do something with the data
}
}
var test = new ObjectA();
test.getData();
答案 0 :(得分:2)
嗯.. that
无法在getData
内部访问,因为它与initialize
的范围不同。重命名this
非常常见,因此它可以在内部范围上下文中使用,并且您最终可能想要使用this
上下文中应该包含的任何onSuccess
,但是你问:
onSuccess: function (response) {
//this is now ObjectA
}.bind(this);
答案 1 :(得分:0)
使用bind()
:
...
onSuccess: function(response) {
this.workData(response.responseText);
}.bind(this)
...