"这"关键字在事件方法中使用JavaScript原型对象时 [英] "this" keyword in event methods when using JavaScript prototype object
问题描述
我正在尝试在事件处理程序中使用JavaScript中的原型类的成员变量进行访问 - 我通常会使用this关键字(或that事件处理程序)。不用说,我遇到麻烦了。
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关键字现在引用事件目标(anchor()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原型对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!