I have a $.fn.sample = function() called by, let’s say $('#example').sample(); so inside the function I could use “this” into it’s scope:
$.fn.sample = function(){
console.log($(this).width());
} //In this case, it would log the width of #example
But let’s say I call a hover function into another element, like this
$.fn.sample = function(){
console.log($(this).width());
$('#other').hover(function(){
//Here, $(this) will refer to #other
});
}
So, inside the hover function “$(this)” will refer to #other, is there a way to use the “parent” $(this)? In this case, the “#example” inside this hover function?
The answer is yes, but not with parent.
A common solution for your question is to use a ‘that’ variable:
}
I believe this was originally proposed by Douglas Crockford, but I am not certain of the origin. The link will give the technical details, but the usage turns out to be very important for ‘private data members’.
Another very important point on Best-Practice…
I really recommend using the pattern but not calling the variable ‘that’.
Here is why:
It is not so important to know -> where a variable came from, but -> what it is.
In practice, a that can be coming from a wrapping scope many lines of code away from the current line in question. From a maintainability standpoint, it is a waste of time to try and figure out what ‘that’ is, and even more frustrating if it is not even known what ‘this’ is. Instead, we should just call it what it is and let the scope be what it is.
For example,
Also, others are using the naming convention of adding a dollar sign.
This is ok, but can be confusing. It is worth mentioning that it indicates the object is a jQuery object.
Hope that helps.