使用JavaScript原型对象时,事件方法中的"this"关键字

Mic*_*ael 12 javascript events this

我试图在事件处理程序中使用JavaScript访问原型类的成员变量 - 我通常使用"this"关键字(或者在事件处理程序的情况下使用"[this of copy]") .不用说,我遇到了一些麻烦.

举个例子,这个HTML片段:

<a id="myLink" href="#">My Link</a>
Run Code Online (Sandbox Code Playgroud)

这个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);
}
Run Code Online (Sandbox Code Playgroud)

实例化MyClass对象并调用NormalMethod的工作方式与我预期的完全相同(警告说"值"),但单击链接会产生未定义的值,因为"this"关键字现在引用事件目标(anchor()HTML元素) .

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

var that = this;
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

ijw*_*ijw 13

你需要:

this.link.onclick = this.EventMethod.bind(this);
Run Code Online (Sandbox Code Playgroud)

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


Cre*_*esh 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.

    };
}
Run Code Online (Sandbox Code Playgroud)


ale*_*dev 5

你应该试试

this.link.onclick = this.EventMethod.bind(this);
Run Code Online (Sandbox Code Playgroud)