关于闭包的一些讲解

廖雪峰:https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/00143449934543461c9d5dfeeb848f5b72bd012e1113d15000#0

阮一峰:http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html

一个PPT:https://www.gracecode.com/posts/2385.html

MDN上的一个例子:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

其中对于this的解释:https://www.quirksmode.org/js/this.html

要理解的两个例子:

 var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  alert(object.getNameFunc()());
var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };
    }
  };
  alert(object.getNameFunc()());

轩脉刃 说:
理解最后两个例子:
1 函数中的this指的是调用这个函数的owner
2 object.getNameFunc()是返回一个函数,并没有执行函数中的代码
3 增加一个例子0:

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
                    return (this.name);
      }
  };
var name = object.getNameFunc();
  alert(name); 

4 把例子1变成

  var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;   //这个this是有上下文的限制的
      };
    }
  };

var tmp = Object.getNameFunc(); //此时没有执行this.name
var name = tmp();//这个时候才执行,这时候的this上下文为全局
alert(name);
//alert(object.getNameFunc()())
5 把例子2变成:

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };
    }
  };

var tmp = Object.getNameFunc(); //这个时候执行了that = this,这里的this上下文是object,所以that指的是object
var name = Object.getNameFunc(); //这个时候执行了that.name
alert(name);
//alert(object.getNameFunc()());

你可能感兴趣的:(关于闭包的一些讲解)