2011-09-10 40 views
0

我有一個對象,我正在加入Strophe的每個房間。該對象包含一個處理這個特定房間的存在段的功能。此參考Strophe節處理程序

function Room(name, someData) 
    this.name = name; 
    this.someData = someData; 

    this.presenceHandler = function(presence) { 
     console.log(this.name, this.someData); 
    } 

    this.join = function() { 
     connection.addHandler(this.presenceHandler,null,"presence",null,null,this.name); 
     connection.send(/*presence*/); 
    } 
} 

var connection = new Strophe.Connection(/*http-bind*/); 
var mainRoom = new Room("main", {foo: "bar"}); 
mainRoom.join(); 

但當mainRoom.presenceHandler()功能由節在函數調用通過的strophe,this指節本身,而不是mainRoom了,所以我無法從mainRoom訪問屬性。

你能告訴我,我如何從presenceHandler函數中訪問房間對象的屬性?

回答

0
 this.join = function() { 
    connection.addHandler(this.presenceHandler,null,"presence",null,null,this.name); 
    connection.send(/*presence*/); 
} 

替換上面的代碼與此

 var thiss=this; 
    this.join = function() { 
    connection.addHandler(function(presence)    
    {thiss.presenceHandler(presence);},null,"presence",null,null,this.name); 
    connection.send(/*presence*/); 
} 

注意關閉的處理程序

1

再試一次初始化主類裏面的函數...

function MainFunc() { 

    this.method1 = function() { 
    this.property1 = "foo"; 
    } 

    this.method2 = function() { 
    var parent = this; // assign the main function to a variable. 
    parent.property2 = "bar"; // you can access the main function. using the variable 
    } 
}