Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This Keyword in a Function Within an Object

So I have most of my functions and variables organized into small object-based modules, like so:

module1: {
  someVariable: false,

  someFunction: function(e) {
     do some stuff using someVariable
  },

  someFunction2: function(e) {
    do some other stuff
  }
}

And I call these functions as callbacks during various events, like so:

$(function() {
  $('.thing').on('mouseenter', module1.someFunction);
}

Now, from within someFunction, I would expect the 'this' keyword to refer to the object in which the function is contained. Instead, it refers to the DOM element that triggered the event that fires the function. Is there anyway I can get access to, say the someVariable variable in the function's containing object other than writing module1.someVariable?

like image 632
user1427661 Avatar asked Jan 25 '26 16:01

user1427661


1 Answers

The shortest answer is to try this:

$(function() {
  $('.thing').on('mouseenter', function(e) {
    module1.someFunction(e);
  });
}

The 'this' value is only set to the object the method is attached to if the method is invoked directly on the object:

module1.someFunction(); // direct invocation, 'this' will be set properly
var tempFunc = module1.someFunction;
tempFunc(); // the function was removed first.  'this' will NOT be set

In your case, you are pealing the method off of the object and handing it to an event handler. The event handler doesn't know about the object and doesn't perform a direct invocation.

In fact, the event handler explicitly overrides the context because that is how the jQuery API is defined. You have to explicitly override it back if you want the behavior you're talking about.

Using a library like underscore.js you could also bind the function as you pass it off to the event handler.

$(function() {
  $('.thing').on('mouseenter', _.bind(module1.someFunction, module1));
}

I believe that Object.bind is supposed to be natively supported in the future with no libraries, but you can't yet rely on the older browsers to support it.

like image 197
Mike Edwards Avatar answered Jan 28 '26 04:01

Mike Edwards



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!