码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 中的闭包

时间:2016-04-25 19:42:19      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

在 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 这个全局对象!

javascript 中的闭包

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!