简体   繁体   English

OOP Javascript,获取类的属性而不是事件 e

[英]OOP Javascript, get attribute of class not the event e

In a event handler from my custom class, I want to use an attribute of my class in a private event method.在我的自定义类的事件处理程序中,我想在私有事件方法中使用我的类的属性。 Its more clearly with this simple example :这个简单的例子更清楚:

 class myClass { constructor() { this._customAtt = "hello"; } foo() { this._addListeners(); } _addListeners() { $("input.two").click(this._anEvent); } _anEvent(e) { console.log(this._customAtt); // print 'undefined' console.log(self._customAtt); // print 'undefined' } } var myIClass = new myClass(); $('input.one').on("click", function() { myIClass.foo(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='button' value='one' class='one'> <input type='button' value='two' class='two'>

When I click on the button one , I add an handler to the button two .当我单击按钮1 时,我向按钮2添加了一个处理程序。 If I click on the button two the method _anEvent is called and from this method, I want use the private attribute class _customAtt .如果我单击两个按钮,将调用_anEvent方法,并且从该方法中,我想使用私有属性类_customAtt But, in the _anEvent method, this is the event e, not my class.但是,在_anEvent方法中, this是事件 e,而不是我的类。

So, how can I can the attribute _customAtt from the method _anEvent ?所以,我怎么能可以在属性_customAtt从方法_anEvent

The reason for this is because the context of this varies depending on how the function is called, not what the function was originally attached to.这样做的原因是因为上下文this取决于该函数的调用,而不是什么功能原本附着。

One relatively easy way to do this is to bind _anEvent to the instance of the class.一种相对简单的方法是_anEvent 绑定到类的实例。

constructor() {
    this._customAtt = "hello";
    this._anEvent = this._anEvent.bind(this);
}

This will ensure that this is always the instance of myClass within the _anEvent function.这将确保this始终是_anEvent函数中myClass的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM