Scope closure: block pattern

 Block pattern requires two necessary conditions
 1. There must be an external closed function, which must be called at least once (each call will create a new module instance)
 2. The closure function must return the at least one internal function, so that the internal function can be formed in the closures private scope, and may access or modify the privacy status and
An object having a function attributes are not actual modules as viewed from the perspective of convenience, and not a subject of the closure function returned by the function, not only real data attributes module
function CoolModule(){
  var something = "cool";
  var another = [1,2,3];
  function doSomething(){
    console.log(something);
  }
  function doAnother(){
    console.log(another.join("!"));
  }
  return{
    doSomething:doSomething,
    doAnother:doAnother
  }
}
var foo = CoolModule();
foo.doSomething(); //cool
foo.doAnother() //1!2!3

  This mode is referred to in JavaScript module. Saicho Save method implemented den open mode is generally referred module is exposed , there is shown a variant, another simple but powerful block pattern usage is changed, it will be designated as a public API returns an object:

var foo = (function CoolModule(id){
    function change(){
      // 修改公共API
      publicAPI.identify = identify2
    }
    function identify1(){
      console.log(id);
    }
    function identify2(){
      console.log(id.toUpperCase());
    }
    var publicAPI = {
      change:change,
      identify:identify1
    }
    return publicAPI;
})("foo Module");

foo.identify()   //foo Module
foo.change()
foo.identify()   //FOO MODULE

  , May be performed by leaving the internal public API object reference example inside the module from the inside of the module instance to modify, add or delete include methods and properties, and modifying their values

Guess you like

Origin www.cnblogs.com/chorkiu/p/12132858.html