1

HTML

<input type="checkbox" class="test" id="chk" /><label for="chk">Click</label>

<p id="demo"></p>

JavaScript

(function (){
 var chk = document.querySelector('.test');

 function ClickTest(elem){
    this.elem = elem;
 };

ClickTest.prototype.addListener = function() {
   this.elem.addEventListener('change', this.showValue);
};
ClickTest.prototype.showValue = function(){
   console.log('Clicked');
   var d = document.getElementById('demo');
   d.innerHTML = "This works";
   this.test();
};
ClickTest.prototype.test = function(){
   console.log('Test function');
};

clickTest = new ClickTest(chk);
clickTest.addListener();
})();

My code works fine before this.test() is called. The error I get is

TypeError: this.test is not a function

Is it because showValue is called from addEventListener or am I doing something wrong here?

  • possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Scimonster Jun 08 '15 at 17:10

1 Answers1

0

Because the addEventListener is invoking the method, it's context is being changed to that of the addEventListener function ( you can console log this on the showValue to test ). This can be fixed (every pun intended) using the bind method:

ClickTest.prototype.addListener = function() {
   this.elem.addEventListener('change', this.showValue.bind(this) );
};

This ensures that the context is maintained. What bind does is essentially forces the method to be called in the scope of what it has been bound to. In our case, we are binding it to ClickTest by passing in this.

Jesse Kernaghan
  • 4,160
  • 1
  • 17
  • 25