官术网_书友最值得收藏!

Modules

Modules are used to mimic classes and focus on public and private access to variables and functions. Modules help in reducing the global scope pollution. Effective use of modules can reduce name collisions across a large code base. A typical format that this pattern takes is as follows:

Var moduleName=function() {
  //private state
  //private functions
  return {
     //public state
     //public variables
  }
}

There are two requirements to implement this pattern in the preceding format:

  • There must be an outer enclosing function that needs to be executed at least once.
  • This enclosing function must return at least one inner function. This is necessary to create a closure over the private state—without this, you can't access the private state at all.

Check the following example of a module:

var superModule = (function (){
  var secret = 'supersecretkey';
  var passcode = 'nuke';

  function getSecret() {
    console.log( secret );
  }

  function getPassCode() {
    console.log( passcode );
  }

  return {
    getSecret: getSecret,
    getPassCode: getPassCode
  };
})();
superModule.getSecret();
superModule.getPassCode();

This example satisfies both the conditions. Firstly, we create an IIFE or a named function to act as an outer enclosure. The variables defined will remain private because they are scoped in the function. We return the public functions to make sure that we have a closure over the private scope. Using IIFE in the module pattern will actually result in a singleton instance of this function. If you want to create multiple instances, you can create named function expressions as part of the module as well.

We will keep exploring various facets of functional aspects of JavaScript and closures in particular. There can be a lot of imaginative uses of such elegant constructs. An effective way to understand various patterns is to study the code of popular libraries and practice writing these patterns in your code.

Stylistic considerations

As in the previous chapter, we will conclude this discussion with certain stylistic considerations. Again, these are generally accepted guidelines and not rules—feel free to deviate from them if you have reason to believe otherwise:

  • Use function declarations instead of function expressions:
    // bad
    const foo = function () {
    };
    
    // good
    function foo() {
    }
  • Never declare a function in a non-function block (if, while, and so on). Assign the function to a variable instead. Browsers allow you to do it, but they all interpret it differently.
  • Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.
主站蜘蛛池模板: 永善县| 兴仁县| 台南市| 海伦市| 武威市| 上犹县| 安平县| 静安区| 彭水| 昆明市| 枞阳县| 唐海县| 桂林市| 永平县| 呼和浩特市| 确山县| 荆门市| 理塘县| 开原市| 东港市| 景德镇市| 比如县| 深水埗区| 简阳市| 精河县| 三江| 漠河县| 洪洞县| 体育| 天气| 扎囊县| 铜陵市| 蚌埠市| 岱山县| 株洲市| 南乐县| 法库县| 泽州县| 平阳县| 东宁县| 平利县|