Reputation: 2498
I'm confused when trying to work out the scope of $(this)
in a jQuery plugin. Take the following simple plugin:
;(function($){
$.fn.somePlugin = function(options) {
// Defaults
var defaults = {
foo: 'bar'
};
// Options
var options = $.extend(defaults, options);
// Return each object
return this.each(function() {
// Cache $(this)
var $this = $(this);
// Do whatever the plugin needs to do here
// A test public function
$.fn.somePublicFunction = function() {
// $this or $(this)?
};
// A test private function
function privateFunction() {
// $this or $(this)?
}
});
};
})(jQuery);
From what I can gather in a private function $this
would use the last index in the array of elements matched so would cause problems. $(this)
is undefined. So if you wanted to reference a specific matched element you would need to pass it to the private function after using some other means to matched the specific element(s) you wish to work with. Or you can do this.each
and loop through all matched elements if you need to.
In the public function, $this is not within scope so you would have to loop through all matched elements with $(this) or this.
Is this correct? Why in $.fn.somePublicFunction
isn't $(this)
available? In general do public functions always apply to all matched elements?
Upvotes: 0
Views: 161
Reputation: 905
this
and $(this)
are the same, and there's no difference in scope.
$(this)
is this
, but only converted to a jQuery object. This way, $(this)
will be visible anywhere, where this
is.
this
can be a DOM element
jQuery sets the scope of the callback function to the element which is the subject of the callback. For example, when you iterating a collection, setting listener or handling an event.
$('#id').on('click', function() {
// this == $('#id')
}
this
can be an Object
For example, when you are iterating a collection of any objects.
var my_arr = [1, 2, 3];
$.each(arr, function(i, obj) {
// 'this' is an object of current iteration
}
this
can be a jQuery object
When you're extending jQuery using fn
extension, this
inside a method is a jQuery object (== $):
$.fn.myPlug = function() {
// this is here a jQuery object, on which the method is called
});
this can also be an AJAX settings Object inside an AJAX query
When you use var $this = $(this);
, you just saving current this
as a jQuery object to a variable with name $this
, and if this
is different in current context, it would not be equal to previously declared $this
.
Upvotes: 1