我在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。我该如何解决这个问题?
答案 0 :(得分: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();
});
};