Reputation: 802
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
Reputation: 664548
There are two solutions:
(function($) {
function MyClass() {...};
$.fn.myPlugin = function(opts) {
var instance = new MyClass();
...
return this;
};
})(jQuery);
jQuery.MyPluginClass = function() {...};
jQuery.fn.myPlugin = function(opts) {
var instance = new jQuery.MyPluginClass();
...
return this;
};
Upvotes: 3
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