0

In the case I have a code structure as follows :

 Thing.prototype = {

    doSomething: function() {
      $(selector).click(this.handleClick.bind(null, this));
    },

    handleClick: function(self, event) {
      console.log(this); //Window
      console.log(self); //Thing
    }

 }

How could one bind the Thing this context to the self argument and still keep the behavior of the this object as if no arguments were bound using the bind method?

Note : I know I can bind this and use e.originalEvent.target to get the behaviour I want but I'm just curious if there is another way

I hope I'm getting through with what I want to achieve, leave a comment if something is ambiguous.

Spyros Mandekis
  • 984
  • 1
  • 14
  • 32

1 Answers1

1

How could one bind the Thing this context to the self argument and still keep the behavior of the this object as if no arguments were bound using the bind method?

You wouldn't use bind for that, because you want this to be dynamic. Instead:

doSomething: function() {
  var self = this;
  $(selector).click(function(e) {
      return self.handleClick.call(this, self, e);
  });
},

During handleClick, this would refer to the element that was clicked, the first argument would be the Thing instance, and the second would be the event:

handleClick: function(self, event) {
  console.log(this);  // The clicked element
  console.log(self);  // The Thing
  console.log(event); // The event
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • That's great, I'm still trying to get around the `bind` behaviour. A thorough explanation of this behaviour from a doc page would be welcome, if anything is available :) – Spyros Mandekis Apr 29 '15 at 12:37
  • @SpyrosMandekis [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) is some nice documentation on .bind() with examples, but T.J. Crowder's link below to the spec should be even more precise, albeit dry. – doldt Apr 29 '15 at 12:40
  • 1
    @SpyrosMandekis: There's [the specification](http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.5). :-) Fundamentally, if you want `this` to be determined when the function is *called*, `bind` isn't the right tool, because it fixes what `this` will be in advance. – T.J. Crowder Apr 29 '15 at 12:40