0

我与 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.

你能告诉我,我如何从 presentHandler 函数中访问房间对象的属性?

4

2 回答 2

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
  }
}
于 2011-11-11T09:00:06.860 回答
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*/);
}

注意处理程序的闭包

于 2012-02-08T11:46:17.373 回答