0
var test = {
        array: [1,2,3,4],
        events: function() {
            document.getElementById("button").addEventListener("click", this.show);
        },
        show: function() {
            console.log(this.array);
        }       
}
test.events();

This object, when i click a button, addEventListener inside events method will be called and calls the show method. Then show method displays my array, but it only shows undefined. How to fix it?

Huy Le
  • 3
  • 2

1 Answers1

0

The cause of your issue is that this actually behaves differently than what you would expect. When the click event handler (i.e. this.show) is executed, the value that is bound to this is not the test object anymore. I can't explain it better than this very good chapter from Kyle Simpson's You Don't Know JS: this & Object Prototypes`.

In your specific case, you would have to make sure that the value bound to this is explicitly set to the test object. You can do so in multiple ways:

  1. Wrap it inside another function and explicitly call the actual callback function:

    element.addEventListener('click', () => this.show());
    
  2. Use Function.prototype.bind() to explicitly bind the this value:

    element.addEventListener('click', this.show.bind(this) );
    
Arnelle Balane
  • 5,022
  • 1
  • 24
  • 30
  • This question is pretty clearly a duplicate (if you've been on StackOverflow a while…) so you should mark it as such rather than answering. Sometimes it's tempting to just post an answer because it's quicker than looking for a good dupe, but it just scatters answers across more questions. – RobG Mar 03 '18 at 08:07
  • @RobG I agree, I apologize for that. I will keep this in mind the next time I answer a question in SO. Thank you for calling it out :) – Arnelle Balane Mar 03 '18 at 08:12