12

我正在尝试在事件处理程序中访问 JavaScript 中原型类的成员变量——我通常会使用“this”关键字(或在事件处理程序的情况下使用“that”[this 的副本]) . 不用说,我遇到了一些麻烦。

举个例子,这个 HTML 片段:

<a id="myLink" href="#">My Link</a>

这个 JavaScript 代码:

function MyClass()
{
  this.field = "value"
  this.link = document.getElementById("myLink");
  this.link.onclick = this.EventMethod;
}

MyClass.prototype.NormalMethod = function()
{
  alert(this.field);
}

MyClass.prototype.EventMethod = function(e)
{
  alert(this.field);
}

实例化 MyClass 对象并调用 NormalMethod 的工作方式与我期望的完全一样(警告说“值”),但是单击链接会导致未定义的值,因为“this”关键字现在引用事件目标(anchor () HTML 元素) .

我是 JavaScript 原型风格的新手,但在过去,使用闭包,我只是在构造函数中复制了“this”:

var that = this;

然后我可以通过“那个”对象访问事件方法中的成员变量。这似乎不适用于原型代码。还有另一种方法可以实现这一目标吗?

谢谢。

4

4 回答 4

13

你需要:

this.link.onclick = this.EventMethod.bind(this);

...'bind' 是 Prototype 的一部分,并返回一个函数,该函数调用您的方法并正确设置了 'this'。

于 2009-09-02T17:20:12.023 回答
9

您的"that=this"闭包习语仍然适用:

function MyClass()
{
    ...

    var that = this;
    this.link.onclick = function() {
        return that.EventMethod.apply(that, arguments);

        // that.EventMethod() works too here, however
        // the above ensures that the function closure
        // operates exactly as EventMethod itself does.

    };
}
于 2009-09-02T17:18:25.413 回答
5

你应该试试

this.link.onclick = this.EventMethod.bind(this);
于 2009-09-02T17:19:55.533 回答
0

如上所述,使用作为 Prototype 库一部分的 bind 是解决此问题的一种简洁方法。这个问题是另一个 SO 问题的副本,这里通过实现 bind 方法回答了这个问题,但不包括整个原型库:

https://stackoverflow.com/a/2025839/1180286

于 2013-10-25T13:33:41.133 回答