类方法无法访问属性 [英] Class method can't access properties
本文介绍了类方法无法访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个类似的类:
I have created a class like so:
function MyClass()
{
var myInt = 1;
}
MyClass.prototype.EventHandler = function(e)
{
alert(this.myInt);
}
不幸的是,这个
是触发事件(在我的casss中是一个标签),我无法访问类属性。
Unfortunately, the this
is the triggered event (in my casss an tag), and i can't access the class properties.
有任何建议吗?
推荐答案
这取决于您在注册活动时如何给予事件处理程序。
It depends on how you are giving your event handler when registering the event.
以下代码
element.addEventListener("click", myObject.EventHandler);
不会做你想做的事。
例如,Javascript不处理像C#这样的委托,因此myObject.EventHandler不是为myObject调用的EventHandler方法。
Javascript does not handle delegates like C# would for example, so myObject.EventHandler is not the EventHandler method called for myObject.
如果要在对象上调用方法作为一个事件处理程序,最好将它包装成一个函数。
If you want to call a method on an object as an event handler, the best is to wrap it into a function.
element.addEventListener("click", function(event)
{
myObject.EventHandler(event);
});
这篇关于类方法无法访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文