天天看点

[JavaStript学习记录] 模块/封装私有变量

模块(用软件工程的方法,管理网页的业务逻辑)

"立刻执行函数"

为了不暴露私有成员,使用"立刻执行函数",将有关的属性、方法封装在一个函数的作用域中

var m = (function () {
 var count = 0;
 var f1 = function () {
   //...
 };
 var f2 = function () {
  //...
 };
 return {
  f1: f1,
  f2: f2
 };
})();


m.count  

>>undefined  //外部代码无法读取内部的count变量      

"放大模式"

情形:

  • 一个模块很大,必须分成几个部分
  • 或者一个模块需要继承另一个模块
var moduleA = (function (mod){
 mod.f = function () {
  //...
 };
 return mod;
})(moduleA);


为模块moduleA添加了一个新方法F(),然后返回新的moduleA模块      

在实际中,模块中的各个方法加载的顺序可能是不同的,若是第一个加载的是不存在的对象,则采用 

"宽放大模式"(立即执行函数的参数可以为空对象)

var module = (function(mod){
    //
    return mod
})({} || window.module);      

全局变量的输入

为了在模块内部调用全局变量,必须显式地将其他变量输入模块

var module = (function ($, YAHOO) {
 //...
})(jQuery, YAHOO);      
//立即执行函数可以起到命名空间的作用

(function($, window, document) {

  function handleEvents() {
      //...
  }

  function initialize() {
      //...
  }

  function destruction() {
      //...
  }
  
  //对外只暴露init和destroy接口
  window.finalAction = {
    init : initialize,
    destroy : destruction
  }

})( jQuery, window, document );      

继续阅读