zoukankan      html  css  js  c++  java
  • 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 这个全局对象!

  • 相关阅读:
    request.getAttribute()和 request.getParameter()的区别
    jquery中$.get()提交和$.post()提交有区别吗?
    jQuery有几种选择器?
    jQuery 库中的 $() 是什么?
    JavaScript内置可用类型
    MySQL数据库中,常用的数据类型
    简单叙述一下MYSQL的优化
    什么是JDBC的最佳实践?
    Vue官网教程-条件渲染
    Vue官网教程-Class与Style绑定
  • 原文地址:https://www.cnblogs.com/oxspirt/p/5432324.html
Copyright © 2011-2022 走看看