12
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);

3 Answers 3

9

Your this value changes in the constructor. You can keep a reference in the selector, and use the reference.

function Foo(elementId, buttonId) {

    /*...*/

    var self = this;
    this.button.addEventListener('click', function(e) {self.bar();}, false);
}

Or a more modern solution that doesn't require a variable would be to use Function.prototype.bind.

function Foo(elementId, buttonId) {

    /*...*/

    this.button.addEventListener('click', this.bar.bind(this), false);
}

The .bind method returns a new bar function with the this value bound to whatever you passed it. In this case, it is bound to the original this from the constructor.

Sign up to request clarification or add additional context in comments.

2 Comments

Important to note that many browsers still commonly-used (e.g. IE 8, Safari <= 5.1, others) do not support Function.prototype.bind: kangax.github.com/es5-compat-table
var self = this; That did it; I didn't even think that 'this' might be referencing the button element. Thanks for your help and the quick response. I'd upvote if I could, but I don't have the rep yet :)
1

this in the event handler is the element that the event was added to.

To access the outer this, you need to store it in a separate variable.

Comments

0

this in the click handler is the button element not the object, use a variable to reference the object, like var self = this;

function Foo(elementId, buttonId) {
    var self = this;
    this.element = document.getElementById(elementId);
    this.button = document.getElementById(buttonId);
    this.bar = function() {dosomething};
    this.button.addEventListener('click', function(e) {self.bar();}, false);
}

3 Comments

I found that for using functions (not classes) in JS, you don't need any this. variables, as all variables you define with let inside the function and all the variables you pass to that function are UNIQUE FOR THAT FUNCTION, so EVENT LISTENERS inside that function work, also the classic for loop example works simply by calling the function and giving it an x parameter
In Oct 4, 2012 at 16:23 we didn't have that option
Yes, let variables were introduced in CS6. But they are a better solution in this case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.