function Foo(elementId, buttonId) {
this.element = document.getElementById(elementId);
this.button = document.getElementById(buttonId);
this.bar = function() {dosomething};
this.button.addEventListener('click', function(e) {this.bar();}, false);
}
var myFoo = new Foo('someElement', 'someButton');
I’d like to add event listeners inside my constructor, but it doesn’t seem to work. Is this something that’s possible with the correct syntax? I always get hung up on the line:
this.button.addEventListener('click', function(e) {this.bar();}, false);
Your
thisvalue changes in the constructor. You can keep a reference in the selector, and use the reference.Or a more modern solution that doesn’t require a variable would be to use
Function.prototype.bind.The
.bindmethod returns a newbarfunction with thethisvalue bound to whatever you passed it. In this case, it is bound to the originalthisfrom the constructor.