简体   繁体   中英

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 . If I click on the button two the method _anEvent is called and from this method, I want use the private attribute class _customAtt . But, in the _anEvent method, this is the event e, not my class.

So, how can I can the attribute _customAtt from the method _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.

One relatively easy way to do this is to bind _anEvent to the instance of the class.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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