javascript 中的闭包

在 javascript 中,函数可以当做参数传递,也可以当做返回值返回。
当一个函数内部返回值为一个函数时, 就形成了闭包。(闭包里面的 this 问题)

如下面代码

Function.prototype.after = function (action) {
    var func = this;
    return function () {
        var result = func.apply(this, arguments);
        action.apply(this,arguments);
        return result;
    };
};

var foo= function(a){
   console.log(a);
}

foo =  foo.after(function(){console.log(2)});
foo = foo.after(function(){console.log(3)});

foo(12);

  可以这样理解: foo1 = foo.after(function(){console.log(2);});
          foo2 = foo1.after(function(){console.log(3);});
          foo2(12); // 当foo2(); 执行的时候,有点类似于递归, fun.apply(this.args);(这个里面递归执行)  action();

          foo2() => foo1();  console.log(3);

                                                                           => foo();console.log(2);  console.log(3);

                                              => console.log(12); console.log(2); console.log(3);

    执行结果是: 12

                             2

           3

闭包里面的 this 问题, 如果上面不用  var func = this;  来保存一下当前的 this 的话,而仅仅是

Function.prototype.after = function (action) {
    
    return function () {
        var result = this.apply(this, arguments);
        action.apply(this,arguments);
        return result;
    };
};

  会报错误: this.apply() is not  a function!

      这是因为 函数 function(){} 里面的this 此时指向的是  window 这个全局对象!

原文地址:https://www.cnblogs.com/oxspirt/p/5432324.html