问题描述
我正在尝试在事件处理程序中访问 JavaScript 原型类的成员变量——我通常会使用this"关键字(或that"[copy of this])事件处理程序).不用说,我遇到了一些麻烦.
I'm trying to access the member variables of a prototype class in JavaScript in an event handler -- something I'd typically use the "this" keyword for (or "that" [copy of this] in the case of event handlers). Needless to say, I'm running into some trouble.
以这个 HTML 片段为例:
Take, for example, this HTML snippet:
<a id="myLink" href="#">My Link</a>
还有这段 JavaScript 代码:
And this JavaScript code:
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"关键字现在引用了事件目标(锚点 ()HTML 元素).
Instantiating a MyClass object and calling NormalMethod works exactly like I expect it to (alert saying "value"), but clicking the link results in an undefined value because the "this" keyword now references the event target (the anchor () HTML element).
我是 JavaScript 原型风格的新手,但在过去,使用闭包,我只是在构造函数中复制了this":
I'm new to the prototype JavaScript style, but in the past, with closures, I've simply made a copy of "this" in the constructor:
var that = this;
然后我可以通过那个"对象访问事件方法中的成员变量.这似乎不适用于原型代码.还有其他方法可以实现吗?
And then I could access members variables in event methods via the "that" object. That doesn't seem to work with prototype code. Is there another way to achieve this?
谢谢.
推荐答案
你的 "that=this"
闭包习语仍然适用:
Your "that=this"
closure idiom is still applicable:
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.
};
}
这篇关于“这个"使用 JavaScript 原型对象时事件方法中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!