Proper syntax when passing $(this) to a jQuery function?

Proper syntax when passing $(this) to a jQuery function?

(I promise!! I have looked at the high volume of responses to this question)

I call aFuncJQ with my <body onload="aFuncJQ">, yet my doMouseEnter function never is seen?

function aFuncJQ() {

	$(document).ready(function () {
		
		$("li").on({
	
			mouseenter: function(evt) {			
				$(this).doMouseEnter(evt);    // bad
				doMouseEnter($(this), evt);   // good
			}
			
		});   // on

	});   // $(document).ready(function () {

}   // aFuncJQ

// bad
function doMouseEnter(evt) {

	var $theLI = $(this);

}

// good
function doMouseEnter($theLI, evt) {

}

???

I am not sure what exactly you are saying. $(this) is going to represent the <li> element that was moused over. So to call the doMouseEnter() method won’t work because there is no doMouseEnter() method defined.

The second call where you do doMouseEnter($(this), evt); will work because again, you are going to be capturing the <li> that triggered the mouse over, wrapped it in a jQuery element using $() and then passing that object over to your stand alone function.

So in short, the “bad” method call is bad because there is no .doMouseEnter function on the jQuery object. The “good” works because you are taking the element that did do the trigger and passing it on to your own stand alone function.

In short $(this).doMouseEnter(evt); is not calling your bad version of doMouseEnter unless you are some how attaching that function onto the object which you are not showing here.

One thing I will also say is that you have to remember that this in the context of JavaScript is very picky and specific. It represents the caller, not always the object itself like you see in many OOP languages. Read up on how this works in Javascript. :slight_smile:

1 Like

100% thanks without exception.

I’ve relearned about using jQuery’s .call, but that adds more carbon than just inserting the two Parma when calling my doMouseOver

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.