简体   繁体   中英

Why is these 2 javascript calls to addEventListener have different result

Can you help me to understand why these two JavaScript functions have different results when console.log(self) is executed?

The first code:

var test = {
  init: function() {
    var self = this;
    document.getElementById('show-button').addEventListener('click', self.showButton, false);
  },

  showButton: function() {
    var self = this;
    console.log(self);
  }
}
test.init();

Will result the following on the console when button show is clicked:

<button type="submit" class="btn btn-default" id="show-button" title="Show the list">Show</button>

Whereas the second code:

var test = {
  init: function() {
    var self = this;
    
    function show() {
      self.showButton();
    }
    
    document.getElementById('show-button').addEventListener('click', show, false);
  },

  showButton: function() {
    var self = this;
    console.log(self);
  }
}
test.init();

Will result the following on the console when button show is clicked:

Object {init: function, showButton: function}

In your first example, you pass self.showButton reference to the addEventListener . It'll then be executed in the context of the element applied to, in this example the button, so this will refer to that button.

In the second example your making a closure to capture your object instance thanks to the show method. So show is applied to the button, and then show calls showButton on your object instance.

To avoid this, you can use the bind function which does this exact job:

 var test = { init: function() { var self = this; document.getElementById('show-button').addEventListener('click', self.showButton.bind(self), false); }, showButton: function() { var self = this; console.log(self); } } test.init();
 <button id="show-button">Show</button>

The difference is due to how you pass the function to the event listener

1) document.getElementById('show-button').addEventListener('click', show, false);

Show is just a function (this = undefined) and this will be bound to the element.

2) document.getElementById('show-button').addEventListener('click', self.showButton, false);

self.showButton is an attribute (type function) which has already this bound to self (test object)

more info

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