javascript - 从内部对象访问父对象

标签 javascript object prototypejs

我想知道是否有一种优雅的方法来执行以下代码,而不必先调用父对象“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);

实际操作:http://jsfiddle.net/ExplosionPIlls/hY3Ca/

关于javascript - 从内部对象访问父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970133/

相关文章:

javascript - 跨度后更改文本

javascript - 如何在 facebook init 函数 javascript 中设置标志?

php - 为什么 SimpleXML 在我使用它时将我的数组更改为数组的第一个元素?

javascript - 添加内容时使可滚动元素保持 "at the bottom"

javascript - 从 mongodb 创建项目数组 - Node js

javascript - 即使页面刷新也永久更改数组

android - 我想从我的调用 Intent 中获取对象列表

c# - 如何设计一个包含查询表中的属性的类?

javascript - 如何通过 javascript 初始化/运行原型(prototype)类

javascript - JS代码$$是什么意思?