Calling function from within jquery plugin
I'm writing my first jquery plugin and wondered what the correct/best practice way of referencing another function from within a plugin was? Is there a better way to define bar
in my plugin scri开发者_StackOverflow中文版pt. Should it be within function($)
? I'd also like it to be available to other plugins within the script.
function bar() {
return 'is this best paractice?';
}
(function($) {
$.fn.foo = function() {
alert(bar());
};
}(jQuery));
Why doesn't something like this work:
(function($) {
$.fn.bar = function() {
return 'is this best paractice?';
};
}(jQuery));
(function($) {
$.fn.foo = function() {
alert(bar());
};
}(jQuery));
Thanks
Functions added to $.fn will be used as jQuery plugins. If you just want to provide a global function from your plugin you add it to $ directly (e.g. $.bar = function() ...).
If you just want use the function internally for your plugin put it within function($). That way you make it available only in that scope (the anonymous function) and not everywhere.
精彩评论