I’m doing a dive into JavaScript, and I am struggling to understand ‘this’ references in actual code. Could someone explain the ‘this’ reference in the following example?
$('#myimage').mouseenter(function() {
$(this).effect('bounce',500);
});
I understand that the ‘this’ keyword refers to whatever ‘owns’ the declaring function. That means that in the following code, the ‘this’ would refer to the object that is returned by the objectFunction function:
var objectFunction = function()
{
var thing = function() { alert(this.toString()); };
return { thing : thing };
}
objectFunction().thing();
Now in the first code, the ‘this’ keyword actually refers to the DOM element ‘myimage’. What I can’t work out is how I would determine that through inspection of the JavaScript. Can someone explain this?
The event in your example is handled by jQuery, not by the Javascript engine. In Javascript, it is possible to set what ‘this’ refers to when calling a function. jQuery uses the .apply method on a function to do this. So when jQuery interprets the selector, it will call your handler function for each matched object, setting ‘this’ to that matched object. E.g.
In the above example, the ‘this’ inside the handler will refer to the dom element with the id of “something”, and the alert will show the text “something”.