0

When assigning a click handler to a button and passing an object that contains a method to handle the click event the function context will not be assigned to the passed in method.

Here is a JS Fiddle that shows my understanding of how to overcome this:
http://jsfiddle.net/b53pk/

<!DOCTYPE html>
<html>
  <body>
    <button id="test">Click Me!</button>

    <script>
      function bind(context,name){
        return function(){
          return context[name].apply(context,arguments);
        };
      }

      var button = {
        clicked: false,
        click: function(){
          this.clicked = true;
          console.log(this.clicked);
          console.log(this);
        }
      };

      var elem = document.getElementById("test");
      elem.addEventListener("click",bind(button,"click"),false);     //#2

    </script>

  </body>
</html>

However, if I'm just using regular objects then this problem doesn't occur.

I'm struggling to understand WHY these two behave differently:
http://jsfiddle.net/4FRg3/

var buttonElement = {
    addHandler : function(fn){
        fn();
    }
}

var handler = {
    clicked : false,
    clickHandler : function(){
        this.clicked = true;
        console.log(this.clicked);

    }
}

buttonElement.addHandler(handler.clickHandler);

Can someone help me understand what the difference is?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2122031
  • 581
  • 5
  • 11
  • 2
    `this` is a special variable that depends on how the function is *called*, not when/how it is *defined*. And your `button.clickHandler` function is called in different ways in these two examples. – Felix Kling Feb 22 '14 at 19:12
  • That is the problem that I am having trouble understanding. What is the difference? To me the code looks very similar. I need perhaps another example of exactly what the difference is. Is it the difference between the handler being invoked later by the user click vs immediately? – user2122031 Feb 22 '14 at 19:27
  • 1
    Have a look at the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). It explains `this` quite well. In your first case, you are calling the function as `button.clickHandler.apply(button)` (`context[name].apply(context, ...`), hence `this` refers to `button` (`context`). In the second case you are calling the function as `fn()`, in which case `this` refers to the global object. *edit:* No, it doesn't have anything to do with *when* the function is called, just *how*. – Felix Kling Feb 22 '14 at 19:34
  • See this for a full description of how **this** works in js: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Jun 08 '15 at 20:13

0 Answers0