简体   繁体   English

最佳编码实践JavaScript

[英]Best Coding Practices JavaScript

I'm doing a JQuery plugin to display messages like growl.To manage these messages have created a class. 我正在做一个JQuery插件来显示诸如growl的消息。要管理这些消息,已经创建了一个类。 Because it is a plugin, there is some problem in creating a global variable to store an instance of this class? 因为它是一个插件,所以创建一个全局变量来存储此类的实例存在一些问题吗?

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命名空间(请注意,每个人现在都可以实例化它,仅当它应该是公共的时才这样做):

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

Globals are generally a no-no. 全球人士通常是禁忌。 See here: 看这里:

http://dev.opera.com/articles/view/javascript-best-practices/#avoidglobals 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. 希望这会有所帮助,可以肯定的是您要的是/想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM