0

I'm now facing a js closure problem. In the code bellow, I'm trying to bind an event handler "getNum" to the button, the problem is that this handler is an attribute in an object, so I read it in a book it says I should put my handler in a closure function like bellow, the problem is that I don't really get it why "this" argument point to the correct object when I put the handler in an anonymous function; And why pass an "event" argument to that function, what does "event" argument referring to, is it the event object when I click the button?

this.num = 9;
var myObj = {
    num : 81;
    getNum : function(){return this.num;}
}
var btn = document.getElementById("my-btn");

// btn.addEventListener("click",myObj.getNum);  this doesn't work cause "this" point to the btn object,which doesn't have num attribute.

btn.addEventListener("click",function(event){
      myObj.getNum(event);
    });//worked, but I don't know why.
Yu Duan
  • 103
  • 1
  • 11
  • 4
    This isn't about closures. It's about `this`. (It's true, though, that the call to `myObj.getNum(event)` is within a closure. It's just not really relevant.) – T.J. Crowder Jun 15 '17 at 13:31
  • `"click",myObj.getNum)` does not work because `myObj.getNum` will return the function without context. So when you pass it as even listener, `this` will point to `window` and not `myObj` – Rajesh Jun 15 '17 at 13:32
  • @deceze: 27 seconds ahead of me. :-) – T.J. Crowder Jun 15 '17 at 13:32
  • Because `this` is decided at *call time* by *how* the function is called; it will get called differently by `addEventListener` if you just pass `addEventListener('click', myObj.getNum)`. And yes, the `event` object represents the click event, but you're not using it at all. – deceze Jun 15 '17 at 13:32
  • @Rajesh that part I have already understand, It is the second part confuses me. – Yu Duan Jun 15 '17 at 13:33
  • @YuDuan: It is a bit confusing. If you call `getNum` directly after retrieving it as a value from an object (`myObj`), then `this` in the call is set to the object you got it from. But if you separate getting `getNum` from the object and calling it (`addEventListener(myObj.getNum)`), `this` isn't set to the object. See the linked question's answers for lots more detail. I've also written a blog article on this: [*You must remember `this`*](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html). – T.J. Crowder Jun 15 '17 at 13:36
  • I get it now, so when it execute on myObj.getNum(event); "this" will point to the "myObj" cause now myObj is the caller – Yu Duan Jun 15 '17 at 13:40
  • "Caller" isn't quite the right word, but you probably got the idea, yes. – deceze Jun 15 '17 at 13:50
  • maybe "execution context" would be more appropriate? – Yu Duan Jun 15 '17 at 13:52
  • No, that as a different meaning in JavaScript. – Felix Kling Jun 15 '17 at 13:59

0 Answers0