Why is these 2 javascript calls to addEventListener have different result -


can guys me understand why these 2 javascript functions have different results when console.log(self) 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 following on console when button show clicked:

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

whereas 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 following on console when button show clicked:

object {init: function, showbutton: function} 

in first example, pass self.showbutton reference addeventlistener. it'll executed in context of element applied to, in example button, this refer button.

in second example making closure capture object instance show method. show applied button, , show calls showbutton on object instance.

to avoid this, can use bind function 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>


Comments

Popular posts from this blog

vue.js - Create hooks for automated testing -

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

serial port - hub4com OVERRUN Error -