I’m working with jQuery and trying to apply some basic Javascript OOP principles to a set of functions that control hover behavior. However, I can’t figure out how to get the "this" keyword to refer to the instance of the object I’m creating. My sample code is:
var zoomin = new Object();
zoomin = function() {
// Constructor goes here
};
zoomin.prototype = {
hoverOn: function() {
this.hoverReset();
// More logic here using jQuery's $(this)...
},
hoverReset: function() {
// Some logic here.
}
};
// Create new instance of zoomin and apply event handler to matching classes.
var my_zoomin = new zoomin();
$(".some_class").hover(my_zoomin.hoverOn, function() { return null; });
The problematic line in the above code is the call to this.hoverReset() inside the hoverOn() function. Since this now refers to element that was hovered on, it does not work as intended. I would basically like to call the function hoverReset() for that instance of the object (my_zoomin).
Is there any way to do this?
Only assigning a function to a property of an object does not associated
thisinside the function with the object. It is the way how you call the function.By calling
you are only passing the function. It will not “remember” to which object it belonged. What you can do is to pass an anonymous function and call
hoverOninside:This will make the
thisinsidehoverOnrefer tomy_zoomin. So the call tothis.hoverReset()will work. However, insidehoverOn, you will not have a reference to the jQuery object created by the selector.One solution would be to pass the selected elements as parameter:
As a next step, you could consider making a jQuery plugin.