模块模式

一:一般创建函数

  function a(){}

  function b(){}

二:但是这样就添加了全局参数,所以我们change

  var o = {

    name : "Nick",

    getName : function(){
    

    }

  }

三:这时候,我们可以在外部重写 o.name 参数,为了安全,继续change

  

 1 var o = function(){
 3   var name = "Nick";
 4     return{
 6       getName : function(){
 8         console.log(name);
 9         }
10      }
11 }();
12 
13 o.getName();

  这个时候name 是o 的一个私有属性,外部无法访问,只能访问 o.getName.通常这种单模式在项目中很常见。

let's  make a distinction between the "this" in diffrent context:

 1     var name = "out";
 2     var o = function(){
 3         var name = "in";
 4         var _this = this;
 5         return {
 6             foo : function(){
 7                 console.log(this);
 8             }
 9         }
10     };
11     o().foo();
12 
13     var o = function(){
14         var name = "in";
15         //var _this = this;
16         return {
17             foo : function(){
18                 console.log(this);
19             }
20         }
21     }();
22     o.foo();
23 
24     var o = function(){
25         var name = "in";
26         var _this = this;
27         return {
28             foo : function(){
29                 console.log(_this);
30             }
31         }
32     }();
33     o.foo();

  第一块跟第二块代码其实一个意思:the result is: o

  第三块立即执行,o 里面的this 就是指window.   所以就算把第二块代码写成:

  

 1     var o = function(){
 2         this.name = "in";   // A   :  var name = "in";
 3         var _this = this;
 4         return {
 5             foo : function(){
 6                 console.log(_this.name);
 7             }
 8         }
 9     }();
10     o.foo();//in   //A   :out

  要牢记一点,函数的this 取决于执行环境,而不是定义的上下文。

  

疯癫不成狂,有酒勿可尝;世间良辰美,终成水墨白。
原文地址:https://www.cnblogs.com/chuyu/p/3254640.html