简体   繁体   English

最佳实践:全局对象与模块

[英]Best practices: Global objects vs modules

I'm currently working on a project and have seen the below code used to store each "Module" (as such) in the window object. 我目前正在研究一个项目,并且看到了下面的代码,这些代码用于在窗口对象中存储每个“模块”(如此)。 I've done a fair amount of Javascript over the years and from my understanding of best practices is that you want to avoid polluting the global namespace. 这些年来,我已经做了很多Java脚本,并且根据对最佳实践的理解,您希望避免污染全局名称空间。 Would this be considered polluting the global namespace? 是否认为这会污染全局名称空间?

(function (global) {
    "use strict";

    // Public methods.
    var exports = {};

    /*
    * Some other configuration / members
    *
    */

    global.Helper = exports.members;
    return exports;

}(window));

I'm accustom to using module pattern to structure my Javascript. 我习惯于使用模块模式来构造我的Javascript。

Example below. 下面的例子。

var module = (function () {

    var defaultOptions = {
        //some options
    };

    var init = function (options) {
        defaultOptions = $.extend(defaultOptions, options, false);

    };

    /*
    * More code
    *
    */

    //public functions
    return {
        init: init
    }


})();

From a best practice stand point am I right in my understanding or have I completely missed the boat? 从最佳实践的角度来看,我是对我的理解还是对这条船完全怀念?

Is it acceptable practice to store each module in the window object? 将每个模块存储在window对象中是否可以接受?

I think it's better to put module in global space, because everyone who will use your module would be forced to use it only with a window variable. 我认为最好将模块放在全局空间中,因为使用模块的每个人都将被迫仅将其与window变量一起使用。

Another reason - do window object will always be defined? 另一个原因-是否总是定义窗口对象?

All of the famous JavaScript modules are defined in global scope: jquery, prototype, yii etc. 所有著名的JavaScript模块都在全局范围内定义:jquery,prototype,yii等。

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

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