闭包

作者: antimony | 来源:发表于2019-03-30 13:35 被阅读0次

    如下代码输出多少?如果想输出3,那如何改造代码?

    var fnArr = [];
    for (var i = 0; i < 10; i ++) {
      fnArr[i] =  function(){
        return i
      };
    }
    console.log( fnArr[3]() ) 
    
    var fnArr = [];
    for (var i = 0; i < 10; i ++) {
      fnArr[i] =  (function(j){
        return function() {
          return j;
        }
      })(i);
    }
    console.log( fnArr[3]() ) 
    

    封装一个 Car 对象。

    var Car = (function(){
       var speed = 0;
       //补充
       return {
          setSpeed: setSpeed,
          getSpeed: getSpeed,
          speedUp: speedUp,
          speedDown: speedDown
       }
    })()
    Car.setSpeed(30)
    Car.getSpeed() //30
    Car.speedUp()
    Car.getSpeed() //31
    Car.speedDown()
    Car.getSpeed()  //30
    
    var Car = (function(){
       var speed = 0;
       function setSpeed(s){
           speed = s
       }
       function get(){
          return speed
       }
       function speedUp(){
          speed++
       }
       function speedDown(){
          speed--
       }
       return {
          setSpeed: setSpeed,
          get: get,
          speedUp: speedUp,
          speedDown: speedDown
       }
    })()
    Car.setSpeed(30)
    console.log(Car.get()) //30
    Car.speedUp()
    console.log(Car.get()) //31
    Car.speedDown()
    console.log(Car.get()) //30
    

    如下代码输出多少?如何连续输出 0,1,2,3,4?

    for(var i=0; i<5; i++){
      setTimeout(function(){
        console.log('delayer:' + i )
      }, 0)
    }
    

    输出 5 5 5 5 5
    连续输出 0,1,2,3,4

    for(var i=0; i<5; i++){
      (function(j) {
        return setTimeout(function(){
        console.log('delayer:' + j )
      }, 0)
      })(i)
    }
    

    如下代码输出多少?

    function makeCounter() {
      var count = 0
    
      return function() {
        return count++
      };
    }
    
    var counter = makeCounter()
    var counter2 = makeCounter();
    
    console.log( counter() ) // 0
    console.log( counter() ) // 1
    
    console.log( counter2() ) // 0
    console.log( counter2() ) // 1
    

    因为counter和counter2有不同的作用域


    补全代码,实现数组按姓名、年纪、任意字段排序。

    var users = [
      { name: "John", age: 20, company: "Baidu" },
      { name: "Pete", age: 18, company: "Alibaba" },
      { name: "Ann", age: 19, company: "Tecent" }
    ]
    
    users.sort(byField('age'))
    users.sort(byField('company'))
    

    先跳过碰到点问题


    写一个 sum 函数,实现如下调用方式。

    console.log( sum(1)(2) ) // 3
    console.log( sum(5)(-1) ) // 4
    
    function sum(a) {
      return function(b) {
        return a + b
      }
    }
    

    函数柯里化-只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。

    相关文章

      网友评论

          本文标题:闭包

          本文链接:https://www.haomeiwen.com/subject/lskjbqtx.html