在OOP Javascript中使用方法的优点

Mad*_*s K 5 javascript oop object

我遇到了一个以奇怪的方式构建的JS文件:

var modal = (function(){
  var method = {};

  // Center the modal in the viewport
  method.center = function () {};

  // Open the modal
  method.open = function (settings) {};

  // Close the modal
  method.close = function () {};

  return method;
}());
Run Code Online (Sandbox Code Playgroud)

我理解将函数包装到"模态"对象中的部分,但为什么要绑定所有函数method然后在结尾处返回它?

Dhr*_*hak 6

这是一种将功能分组为模块并摆脱全局变量的设计模式.这导致更好的代码.

  1. 函数调用创建一个'闭包',即在该函数中声明的所有变量的范围,它们甚至在函数退出后仍然存在,并且它们在函数外部不可见.

           var modal = (function(){
           var method = {};
           // Center the modal in the viewport
           method.center = function () {};
    
          // Open the modal
          method.open = function (settings) {};
    
          // Close the modal
          method.close = function () {};
    
          return method;
        }());  // This function call here creates a "closure" ( scope ) 
    
    Run Code Online (Sandbox Code Playgroud)
  2. 现在要使模块的某些成员在模块外部可用,它们需要从函数返回,这里return method确实是这样,制作method模块的公共对象,可以在外面使用.

  3. 不是创建类似于等的变量open,而是close将相关函数作为属性(对象的键)分配给主method对象,以便返回单个对象使得所有相关函数都可访问.这也有助于减少闭包范围内的标识符(名称)的数量.

阅读这篇关于这种modular模式的非常好的文章:

http://www.yuiblog.com/blog/2007/06/12/module-pattern/