I decide to write a plugin, but there is a moment I don’t know,and i can’t find documentation about it so I decide to ask here.
For example when we wrote
$("#some_element").nameOfPlugin();
There are a lot of functions in nameOfPlugin, but how some_element connects with the plugin?
An example, or a link to some documentation will be very helpful.
Thanks.
nameOfPluginis the prototypal method which when inserted with the script element, extends jQuery so any jQuery objects can contain the method.All the internal code of
nameOfPluginhappens inside of that prototypal method and the scope which is defined.Simple example of how you are extending jQuery, using Human instead of jQuery.
As far as
$()connecting to it,$()returns an array of DOM elements ( one or many ). The plugin gets invoked in the context of each of these, since the object owns the method because it is an instance of the jQuery constructor which owns the plugin methods you’ve been adding.$('body').hide()translates to calling the jQuery.prototype.hide method usingdocument.bodythe DOM reference as the context.I suggest reading up on prototypal inheritance to understand this. A good resource would be Eloquent JS, particularly chapter 8.