1
<div id="menu">
  <div>foo</div>
  <div>bar</div>
</div>

Is it possible to access the this that refers to thing rather than the this that refers to the div that was clicked on, inside the event handler method handleClick?

Note: I need to access both thiss inside handleClick

$(document).ready(function() {

    var thing = {
        menu: $("#menu"),

        init: function() {
            var _this = this;
            this.doSomething();
            this.menu.on("click", "div", this.handleClick);
        },

        doSomething: function() {
            console.log(this); // thing
        },

        handleClick: function() {
            console.log(this); // div that was clicked on
            // How to console.log(_this) i.e. thing ?
        }
    };
    thing.init();
});
binaryfunt
  • 6,401
  • 5
  • 37
  • 59
  • Of course, in your setup you could [simply refer to it using `thing` instead of `this`](http://stackoverflow.com/a/10711164/1048572) or `_this` or something like that – Bergi Oct 12 '16 at 23:08
  • And to get access to the clicked div, you could also use [`e.currentTarget`](http://api.jquery.com/event.currentTarget/) - so no `this` at all. – Bergi Oct 12 '16 at 23:12

1 Answers1

0

The standard way is to wrap it and turn that _this variable into something used in a closure:

this.menu.on("click", "div", function() {
  _this.handleClick();
});

Now it's bound correctly to the original this.

You probably want to add an argument to capture what was clicked:

this.menu.on("click", "div", function(ev) {
  _this.handleClick(ev, this);
});

Then ensure your method receives this:

handleClick: function(ev, target) {
  // ev = Event generated
  // target = The target clicked
}
tadman
  • 208,517
  • 23
  • 234
  • 262
  • This seems to be the cleanest thing I've seen all day, without unnecessarily getting further confused by `this`! – binaryfunt Oct 12 '16 at 23:25
  • Yes, this works, but this is a sloppy hack and is very bad practice. You don't need to rewrite all your class code to use _this instead of this. – Cerin Jun 05 '21 at 05:05
  • @Cerin This was from 2016. Things have changed. – tadman Jun 05 '21 at 09:53