jQuery plugin authoring: explanation for "this" keyword?
I've been coding with jQuery for about 2 years now but I've never done it in a plugin. I'm trying to chan开发者_StackOverflow社区ge this. I found a few websites that explain how to create a plugin and I understand the basics.
The part that I don't understand is the use of the this
keyword. Here's a simple plugin example:
(function($){
$.fn.myPlugin = function(options)
{
// Do whatever
return this.each(function(){
element = $(this);
});
}
$.fn.myPlugin.init = function()
{
// Initiate plugin
}
})(jQuery);
On the 5th line of my code, I have this.each
. In this case, the this
keyword refers to all the elements in the selector. The following line uses $(this)
which is the current element, the same way as if I do it in a .click(function(){$(this).hide();})
.
Now, in the OO logic, usually we have a this
keyword to refer to internal functions or properties. If in $.fn.myPlugin
I want to call $.fn.myPlugin.init()
, I expected to be able to do with something like this.init()
but it doesn't seem to be working.
Also, I was expecting to be able to define class properties in a similar way, something like this.myVariable = "my value"
.
So if anyone can explain whatever I'm missing to understand the plugin concept with jQuery, or point me in the right direction with a relevant link, I'd appreciate the help! If my explanations are not clear enough, let me know and I'll try to make it better, but it's kind of blurry in my mind right now. ;)
Before you get into the .each()
, this
is actually the jQuery object that contains the set of matched DOM elements.
If you wanted to call that function in that manner, you would need to call it in the scope to which it was added. $.fn.myPlugin
.
this.myPlugin.init();
or inside the each like this:
$(this).myPlugin.init();
Or directly like this:
$.fn.myPlugin.init();
精彩评论