A closure is when you're using a variable inside a function whose declaration resides outside of it:
var foo = 'bar';
function baz(){
alert(foo);
}
Since there are plugins popping out everywhere, my suggestion to keep namespace clean is similar to what jQuery does itself: use your own namespace, then use an alias to attach it:
var myFooBarNamespace = {
myMethod : function(){}
};
jQuery.fn.myMethod = myFooBarNamespace.myMethod;
this makes it easier to address collisions since you would only need to have to change the aliases, not all the calls within the plugin code itself. This alias section could even see if there are already colliding plugins and do something about it, very much like jQuery does with $.
I hope I didn't say something completely stupid while trying to clarify scopes and closures. Feel free to call me an idiot (but only if i'm wrong on THIS)
-brito
On 9/8/06,
Jörn Zaefferer <[EMAIL PROTECTED]> wrote:
Sam wrote:
> The plugin skeleton shown below is taken from the plugin model overview at:
> http://jquery.com/plugins/Authoring/
>
That is only one approach. It uses a closure (the "new function()
{[code]}()" syntax) to hide variables and functions. You could as well
use the second approach mentioned there, avoiding the closure. That
maybe easier to understand if you are not familiar with scopes in
general and closures in detail.
> 1 - I see jQuery coders like to encapsulate code in autonomous functions, but I haven't read anything about why, and I'm not clear
> on why. The benefit would be that locally declared variables aren't externally visible? That is, wouldn't the following code
> perform as well?
>
The basic idea behind all this "hiding" is to prevent namespace
collisions. In other words: You don't want to overwrite other functions
or variables and vice-versa, as this could cause serious trouble that is
hard to find. To prevent collisions, every plugin author should expose
only no more global functions or variables then absolutly necessary.
> 2 - The documentation describes the $.myplugin.publicmethod1 as being a technique for coding "private" functions.
> And on a related note, if we like documentation with public/private in the names to improve the clarity, why isn't
> $.fn.mypluginmethod (in 1 above) named $.fn.myPublicMethod?
>
The names in the example are only choosen to show which functions are
public and which are private. The scope is only defined by the context
and syntax, not the name itself.
Please correct me if I'm wrong, I learned most of this stuff in the last
two months myself :-)
-- Jörn
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/
_______________________________________________ jQuery mailing list [email protected] http://jquery.com/discuss/
