3

According to John Resig's 'Learning Advanced JavaScript' (http://ejohn.org/apps/learn/#83) it's incorrect to bind an object's method to event handler without passing the original object as context, however I find the example flawed. It claims the clicked property gets set accidentally. Here's a counter-example.

var Button = {
  click: function(){
    this.clicked = true;
    console.log( elem.clicked );
  }
};

var elem = document.createElement("li");
elem.innerHTML = "Click me!";
elem.onclick = Button.click;
document.children[0].appendChild(elem);

console.log( !elem.clicked );

There must be another reason not to do this. What is it?

Ivan Vashchenko
  • 1,214
  • 2
  • 11
  • 19
  • Also you skipped the very important line of code in that example, where the "click" event was actually triggered. In your code above, the "click" function will never even be called. – Pointy Dec 14 '13 at 17:35
  • it's not "wrong" if it works, it's just potentially confusing to other coders... – dandavis Dec 14 '13 at 18:09