I’ve run into this a few times now. I’ve tried to create the simplest code snippet I could to demonstrate it.
The problem is, inside and object method, if I pass an anonymous function to a jQuery method (like an “each”), inside of the function, I lose access to the object’s “this”. Because “this” is now related to the jQuery object.
See the comments in the middle of the logNameAndElementIds method for the crux of the problem:
(I’m using Crockford’s object function to produce an object instance based on an object defined with an object literal.)
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
var objectLiteral = {
setName: function(name){
this.name = name;
},
logNameAndElementIds: function(){
// works fine, 'this' refers to object instance
console.log( this.name );
$('.foo').each(function(){
// we've lost "this" because it now refers to jQuery
console.log( this.name );
console.log( $(this).attr('id') );
});
}
};
obj1 = Object.create(objectLiteral);
obj1.setName('Mike');
obj1.logNameAndElementIds();
What’s the right way to handle or workaround this sort of situation?
Obviously my example is stupid, but it’s just to demonstrate a point. More often I want to loop through a jQuery matched set, then call a method of the containing object on each item. But I can’t access the object’s method, because I now have jQuery’s “this”.
I think there is a better answer to this than the one I previously accepted, and that is to use ES5’s new Function.prototype.bind method. Much cleaner, available in all modern browsers, and easy to shim for older browsers.
With bind() you can do stuff like this:
A minified version of the Mozilla shim (which seems to be the best around) is: