2012-05-17 1 views
0

Я определил два класса в javascript следующим образом.Невозможно вызвать метод класса javascript из блока ответа FB.api

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» в this.one() ссылается на функцию обратного вызова 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

Работы! ...... :) – serpent403

Смежные вопросы