0

我在javascript中定义了两个类,如下所示。

function ParentClass(){
    this.one = function(){
      alert('inside one of parent');
    };

    this.two = function(){
       alert('inside two of parent');
       //this is just a skeleton of the actual FB.api implementation in my code
       FB.api('/me', 'post', function(response){
        this.one();
      });

    };

}

function ChildClass(){
    ParentClass.call(this);

    //overriding the one() in ParentClass
    this.one = function(){
      alert('inside one of child');
    };
}


ChildClass.prototype = new ParentClass();
ChildClass.prototype.constructor = ChildClass;
var c = new ChildClass();
c.two(); 

the last line calls the ParentClass's two() method which then calls the one() method overriden by the ChildCLass.

我收到一条错误消息,提示“this.one() 未定义”。但是当我将 this.one() 方法放在 FB.api 响应块之外时,该函数会被完美地调用。我认为问题可能是 this.one() 中的“this”指的是 FB.api 回调函数而不是 ChildClass。我该如何解决这个问题?

4

1 回答 1

2

只需将副本存储this在 FB 调用之外的另一个变量中。

this.two = function(){
   alert('inside two of parent');
   //this is just a skeleton of the actual FB.api implementation in my code
   var self = this;
   FB.api('/me', 'post', function(response){
    self.one();
  });

};
于 2012-05-17T14:22:00.167 回答