Javascript modular programming (1): module writing

As websites gradually became " Internet applications ", the Javascript code embedded in web pages became larger and more complex.

Web pages are becoming more and more like desktop programs, requiring a team of division of labor, progress management, unit testing, etc... Developers have to use software engineering methods to manage the business logic of web pages.

Javascript modular programming has become an urgent need. Ideally, developers only need to implement core business logic, and others can load modules already written by others.

However, Javascript is not a modular programming language, it does not support " class " (class), let alone "module" (module). (The sixth edition of the ECMAScript standard , which is under development , will officially support "classes" and "modules", but it will be a long time before it becomes practical.)

The Javascript community has made a lot of efforts to achieve the effect of "module" in the existing runtime environment. This article summarizes the current best practices for "modular programming in Javascript" and shows how to put them into practice. Although this is not an elementary tutorial, you can understand it as long as you have a little understanding of the basic syntax of Javascript.

First, the original writing

A module is a set of methods that implement a specific function.

Simply put together different functions (and variables that keep track of state) together, and it's a module.

  function m1(){
    //...
  }

  function m2(){
    //...
  }

The above functions m1() and m2() form a module. When using it, just call it directly.

The disadvantage of this approach is obvious: it "pollutes" global variables, there is no guarantee that there will be no variable name conflicts with other modules, and there is no direct relationship between module members.

Second, the object writing

In order to solve the above shortcomings, the module can be written as an object, and all module members are placed in this object.

  var module1 = new Object({

    _count : 0,

    m1 : function (){
      //...
    },

    m2 : function (){
      //...
    }

  });

The above functions m1() and m2() are encapsulated in the module1 object. When used, it is to call the properties of this object.

  module1.m1();

However, this way of writing exposes all module members, and the internal state can be overwritten externally. For example, external code can directly change the value of an internal counter.

  module1._count = 5;

3. Immediately execute the function writing method

Using " Immediately -Invoked Function Expression" (IIFE) can achieve the purpose of not exposing private members.

  var module1 = (function () {

    var _count = 0;

    var m1 = function () {
      // ...
    };

    var m2 = function(){
      //...
    };

    return {
      m1 : m1,
      m2 : m2
    };

  })();

Using the above writing method, the external code cannot read the internal _count variable.

  console.info(module1._count); //undefined

module1 is the basic way of writing Javascript modules. Next, this writing method is processed again.

Fourth, the zoom mode

If a module is large and must be divided into several parts, or if one module needs to inherit another module, then it is necessary to use "augmentation".

  var module1 = (function (mod) {

    mod.m3 = function () {
      //...
    };

    return mod;

  })(module1);

The above code adds a new method m3() to the module1 module and returns the new module1 module.

5. Loose augmentation

In a browser environment, the various parts of a module are usually fetched from the web, and sometimes there is no way to know which part will load first. If the writing method in the previous section is used, the first executed part may load a non-existent empty object, then the "wide enlargement mode" should be used.

  var module1 = (function (mod) {

    //...

    return mod;

  })(window.module1 || {});

Compared with "magnification mode", "wide magnification mode" is that the parameter of "execute function immediately" can be an empty object.

6. Enter global variables

Independence is an important feature of modules, and it is best not to directly interact with other parts of the program inside the module.

In order to call global variables inside a module, other variables must be explicitly entered into the module.

  var module1 = (function ($, YAHOO) {

    //...

  })(jQuery, YAHOO);

The module1 module above needs to use the jQuery library and the YUI library, and input these two libraries (actually two modules) as parameters into module1. In addition to ensuring the independence of modules, this also makes the dependencies between modules obvious. For more discussion of this, see Ben Cherry's famous article "JavaScript Module Pattern: In-Depth" .

Part 2 of this series will discuss how to organize different modules and manage dependencies between modules in a browser environment.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324650778&siteId=291194637