this vs $(this) in jQuery

I don’t know why, but this is how it happens.

When I make a jQuery plugin, the skeleton is

(function($) {
$.fn.myplugin = function() {
return this;
};
})(jQuery);

And if I need an each operation inside plugin, the skeleton can be

(function($) {
$.fn.myplugin = function() {
//outside each, this.width() can work
return this.each(function() {
//inside each, only $(this).width() works
});
};
})(jQuery);

The interesting thing is inside each, I must use “$(this)” to run jQuery functions, but outside each, I can also use “this”.

I don’t know why now, but I think I will know some day.

Leave a Reply

Your email address will not be published. Required fields are marked *