这两种JavaScript模式有什么区别? [英] What's the difference between these two JavaScript patterns

查看:92
本文介绍了这两种JavaScript模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更好地整理我的JavaScript。我的目标是拥有模块化的架构,我可以分为单独的文件(sitename.js,sitename.utils.js等)。

I am trying to organize my JavaScript better. My goal is to have modular architecture that I can break into separate files (sitename.js, sitename.utils.js etc).

我想知道这两种模式的优点和缺点,哪一种更适合分解在单独文件中的模块。

I'd like to know what are advantages and disadvantages of these two patterns and which one is more suitable for breaking into modules that live in separate files.

PATTERN#1(模块模式)

PATTERN #1 (module pattern)

var MODULE = (function () {

    //private methods

    return {
        common: {
            init: function() {
                console.log("common.init");
            }
        },
        users: {
            init: function () {
                console.log("users.init");
            },
            show: function () {
                 console.log("users.show");
            }
        }
    }
})();

PATTERN#2(singleton)

PATTERN #2 (singleton)

var MODULE = {
  common: {
    init: function() {
        console.log("common.init");
    }
  },

  users: {
    init: function() {
      console.log("users.init");
    },

    show: function() {
      console.log("users.show");
    }
  }
};


推荐答案

个人而言,我推荐#1的扩展名,如下:

Personally, I recommend an extension of #1, as follows:

var Module = (function(Module) {
  // A comment
  Module.variable1 = 3;

  /**
   * init()
   */
  Module.init = function() {
    console.log("init");
  };

  // ...

  return Module;
})(Module || {});

我喜欢这种模式有几个原因。一个,当所有的函数都是声明而不是一个大的哈希时,文档(特别是javadoc样式)看起来更自然。二,如果你的子模块大小增加,它可以让你将它们分解成多个文件,而无需任何重构。

I like this pattern for a couple reasons. One, documentation (specifically javadoc-style) look more natural when all your functions are declarations rather than a big hash. Two, if your submodules grow in size, it lets you break them into multiple files without any refactoring.

例如,如果Module.Users进入自己的文件:

For example, if Module.Users were to go into its own file:

var Module = Module || {};
Module.Users = (function(Users) {
  /**
   * init()
   */
  Users.init = function() {
    console.log("Module.Users.init");
  };

  // ...

  return Users;
})(Module.Users || {});

现在,module.js和module.users.js可以是单独的文件,而他们无论他们加载的顺序如何,都会工作。另请注意模块名称的局部范围 - 如果您的模块名称很长,这是非常方便的,因为您可以使用MyApp.Users.EditScreen,并在模块定义范围内使用像ES这样的变量引用它。

Now "module.js" and "module.users.js" can be separate files, and they'll work regardless of the order they are loaded. Also note the local scoping of the module name - this is very handy if your module name is long, because you can take "MyApp.Users.EditScreen" and refer to it with a variable like "ES" within the scope of your module definition.

这篇关于这两种JavaScript模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆