I’m trying to understand the scope of $(this) in a jQuery plugin. Here’s a very 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);
When you loop through all of the matched elements (.each) I am caching $(this) to $this. When calling functions (per my two example functions) should you always use $(this) and not my cached $this? If so, is this because you will always end up working with the last matched element in the array?
I’ve always found the jQuery plugin structure a bit confusing!