我想知道是否有一种优雅的方法来执行以下代码,而不必先调用父对象“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();
最佳答案
嗯.. that
无法在 getData
内部访问首先,因为它的范围与 initialize
不同。 。重命名 this
很常见因此它可以在内部作用域上下文中使用,您可能最终想要使用任何 this
应该在onSuccess
中无论如何,但既然你问了:
onSuccess: function (response) {
//this is now ObjectA
}.bind(this);
关于javascript - 从内部对象访问父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970133/