2012-05-17 26 views
0

我已經在javascript中定義了兩個類,如下所示。無法從FB.api響應塊調用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。我該如何解決這個問題?

回答

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(); 
    }); 

}; 
+0

Works!...... :) – serpent403