私は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()
機能が詩句によってスタンザによって呼び出されたときに、関数内this
はもうスタンザ自体にではなくmainRoom
を意味し、私はmainRoom
から属性にアクセスすることはできません。
roomHandler関数内からルームオブジェクトの属性にどのようにアクセスできますか教えてください。ハンドラのために、この
var thiss=this;
this.join = function() {
connection.addHandler(function(presence)
{thiss.presenceHandler(presence);},null,"presence",null,null,this.name);
connection.send(/*presence*/);
}
ノートとコードの上にクロージャを交換してください
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
}
}