2

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 script. 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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That makes sense. But how come this has no effect $.bar = function() { return 'is this best paractice?'; } (function($) { $.fn.foo = function() { alert(bar()); }; }(jQuery));? Wheras if I use function bar() { it does?
Well because in your first example bar() is in global scope meaning that you can call it from anywhere. In the second example if you use $.bar = function() you also will have to call $.bar();
Aain that makes sense but I can't seem to get it work jsfiddle.net/2g8Dg/3
Ups, you have to use $.extend to add global properties and using extend is generally cleaner: jsfiddle.net/2g8Dg/5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.