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?
-
2You're going to need to provide a lot more information than this if you want SO to be able to help. Show some code, some specific issues (or error messages) that are coming up, and tell us what you've tried that hasn't worked.kingcoyote– kingcoyote2012年06月27日 19:24:10 +00:00Commented Jun 27, 2012 at 19:24
-
are you creating this so you can use it in your application? if you are maybe you should look at jGrowl :)c0deNinja– c0deNinja2012年06月27日 19:27:47 +00:00Commented Jun 27, 2012 at 19:27
-
I made the plugin for some time, but is having some bugs and want to improve it lucasmerencia.github.com/JQuery-Growl-PluginLucas Merencia– Lucas Merencia2012年06月27日 19:43:02 +00:00Commented Jun 27, 2012 at 19:43
2 Answers 2
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;
};
2 Comments
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.