闭包的10种形式

 

1.返回值

var fn = function (){
  var name = 'asd';
  return function(){
    return name;
  }
}

var fnc = fn();
console.log(fnc());

 

2.函数赋值 一种变形的形式 是将内部函数赋值给一个外部的变量

var fn2;
var fn = function(){
  var name = 'waw';
  var a = function(){
    return name;
  }
  fn2 = a;
}
fn();
console.log(fn2());

 

3.函数参数

function fn2(f){
  console.log(f());
}
function fn(){
  var name = 'uuj';
  var a = function(){
    return name;
  }
  fn2(a);
}
fn();


 

4. IIFE 立即执行函数

function fn3(f){
  console.log(f());
}

(function(){

  var name = 'alex';
  var a = function(){
    return name;
  }
  fn3(a);
})();


 

5.循环赋值

function foo(){

var arr = [];
for(var i = 0; i < 10; i++){

// (function(i){
// arr[i] = function(){
// return i;
// }
// })(i);

arr[i] = (function(n){
return function(){
return n;
}
})(i);

}
return arr;
}
var bar = foo();
console.log(bar);
console.log(bar[3]());

 

 

6 getter setter  ,将要操作的变量保存在函数内部,防止暴露在外部

var getValue,setValue;
(function(){
     var num = 0;
     getValue = function (){
           return num;
     }
      setValue = function (v){
            if (typeof v=== 'number'){
              num = v;
} } })();
console.log(getValue());
setValue(10);
console.log(getValue());



 

7.迭代器

//计数器
var add = function(){
var num = 0;
return function (){
return ++num;
}
}();
console.log(add());
console.log(add());


//
function setUp(arr){
var i = 0;
return function (){
return arr[i++];
}
}

var next = setUp(['a1','a2','a3']);
console.log(next());
console.log(next());
console.log(next());


 

8 . 区分首次

var firstLoad = (function(){
var list = [];
return function(id){
if (list.indexOf(id) >= 0){
return false;
  }else{
      list.push(id);
       return true;
    }
}
})();
firstLoad(19); // true
firstLoad(19); // false

 

 

 

9. 缓存机制

   未加入缓存:
    
    function mult(){
    
    var sum = 0;
    for(var i= 0;i < arguments.length;i++){
      sum = sum + arguments[i];
    }
    return sum;
  }

    console.log(mult(1,2,3,1,1,2,3));
    console.log(mult(1,2,3,1,1,2,3));
  有缓存的:

  var mult = function(){
    
    var cache = {};
    var calculate = function(){
      var sum = 0;
      for (var i= 0;i < arguments.length;i++){
        sum = sum + i;
      }
      return sum;
    }
     return function(){

      var args = Array.prototype.join.call(arguments,',');
      if (args in cache){
        return cache[args];
       }
      console.log(args);
      return cache[args] = calculate.apply(null,arguments);
    }

}();
  
  console.log(mult(1,2,3,1,1,2,3));
  
  console.log(mult(1,2,3,1,1,2,3));

 

10. img图片对象上报






var report = function(src){
     var imgs = [];

     return function (src){
          
          var  img = new Image();
          imgs.push(img);
          imgs.src = src;

    }
    

}();   

report('http:xxx.com/getinfo');

 

posted @ 2020-11-14 19:06  AngDH  阅读(257)  评论(0编辑  收藏  举报