I’m not very used to javascript’s prototyping syntax so this might be very simple.
function MyClass(){
this.init = function(input){
this.input.onkeyup = function(){
this.change();
}
}
}
Obviously I’ve left some things out here, but this.input refers to an HTML input element. The problem here is that this in this.change() will no longer refer to the instance of MyClass but to the HTML-element. How can I get the object instead of the element?
Event handlers automatically point the
thiskeyword to the element the event is firing on. ECMA-262 5th Edition attempts to combat situations like this by implementing an old technique of “binding” a function to a specific object:Usage:
The ECMAScript implementation is the same as the PrototypeJS implementation (for which the code is above).
You could also implement it on a per-class basis:
The archaic 😉 option is to just store a reference to
thisoutside of the function: