Lucas Merencia
Lucas Merencia

Reputation: 802

Best Coding Practices JavaScript

I'm doing a JQuery plugin to display messages like growl.To manage these messages have created a class. Because it is a plugin, there is some problem in creating a global variable to store an instance of this class?

Upvotes: 2

Views: 211

Answers (2)

Bergi
Bergi

Reputation: 664548

There are two solutions:

  • Make the class a private/local variable in a closure's scope (the standard):

(function($) {
    function MyClass() {...};
    $.fn.myPlugin = function(opts) {
        var instance = new MyClass();
        ...
        return this;
    };
})(jQuery);
  • Use the jQuery namespace for the class (Note the everyone can instantiate it now, do this only if it should be public):

jQuery.MyPluginClass = function() {...};
jQuery.fn.myPlugin = function(opts) {
    var instance = new jQuery.MyPluginClass();
    ...
    return this;
};

Upvotes: 3

MoDFoX
MoDFoX

Reputation: 2134

Globals are generally a no-no. See here:

http://dev.opera.com/articles/view/javascript-best-practices/#avoidglobals

Essentially, they clutter namespace and leave you open to having your global overwritten elsewhere being as your variables may end up falling under the same scope as other scripts. That website also provides some good examples as to how to deal with this.

So in conclusion, best practice is to not use global variables, but instead put them in their own namespace. Hope this helped, pretty sure that's what you were asking for/about.

Upvotes: 2

Related Questions