这在另一个对象的事件处理程序中

时间:2010-01-17 02:00:07

标签: javascript

A类(我的)实现了B类(第三方)的事件处理程序。在这些事件处理程序中,我想访问A类的属性。

在A类的处理程序中使用 this 不起作用,因为它引用了B类的范围。

全局变量似乎是唯一的选择。我错过了一个更好的选择吗?

2 个答案:

答案 0 :(得分:5)

创建selfthat变量,该变量包含对this的引用。像这样:

var ClassA = function () {
    var self = this;

    this.MyProperty1 = 3;
    self.MyProperty2 = "hello world";

    var ClassB_EventHandler = function () {
        self.MyProperty1;
        self.MyProperty2;
    }

}

您可以在this的范围内互换使用selfClassA。在ClassB事件处理程序中,您需要使用self来引用ClassA属性。

答案 1 :(得分:2)

另一种解决方案是将事件处理程序绑定到您的对象!

首先需要将bind方法添加到任何函数对象。使用此代码:

Function.prototype.bind = function(scope) {
  var func = this;

  return function() {
    return func.apply(scope, arguments);
  }
}

现在,您可以通过以下方式向class B方法注册class A事件处理程序:

var a = new A();
var b = new B();

b.registerEvent(a.eventHandlerMethod.bind(a));

这样,this代码中对A.eventHandlerMethod的任何引用都将指向对象a

如果您需要更深入地了解这些内容,可以阅读这篇精彩的文章:http://www.alistapart.com/articles/getoutbindingsituations/

另一篇文章:http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding

相关问题