美文网首页
箭头函数和立即执行函数

箭头函数和立即执行函数

作者: 我是Msorry | 来源:发表于2021-01-05 09:00 被阅读0次

    箭头函数

    箭头函数和普通函数有什么区别?如果把箭头函数转换为不用箭头函数的形式,如何转换
    主要是this的差别,箭头函数里面的this是外面的this。 转换案例

    箭头函数和普通函数的主要区别是箭头函数的 this 是外部环境的

     const obj = {
         a: 1,
         fn: () => {
             console.log(this.a)
         }
     }
    //转换成
     var _this = this
     var obj = {
         a: 1,
         fn: function fn() {
             console.log(_this.a)
         }
     }
    

    箭头函数内定义的变量及其作用域

    // 常规写法
    var greeting = () => {let now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
    greeting();          //"Good day."
    console.log(now);    // ReferenceError: now is not defined 标准的let作用域
    
    // 参数括号内定义的变量是局部变量(默认参数)
    var greeting = (now=new Date()) => "Good" + (now.getHours() > 17 ? " evening." : " day.");
    greeting();          //"Good day."
    console.log(now);    // ReferenceError: now is not defined
    
    // 对比:函数体内{}不使用var定义的变量是全局变量
    var greeting = () => {now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
    greeting();           //"Good day."
    console.log(now);     // Fri Dec 22 2017 10:01:00 GMT+0800 (中国标准时间)
    
    // 对比:函数体内{} 用var定义的变量是局部变量
    var greeting = () => {var now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
    greeting(); //"Good day."
    console.log(now);    // ReferenceError: now is not defined
    

    立即执行函数

    1. 声明一个匿名函数
    2. 马上调用这个匿名函数
    !function(){}()
    

    作用

    创建一个独立的作用域,即避免变量污染

    var liList = ul.getElementsByTagName('li')
    for(var i=0; i<6; i++){
      liList[i].onclick = function(){
        alert(i) // 为什么 alert 出来的总是 6,而不是 0、1、2、3、4、5
      }
    }
    
    var liList = ul.getElementsByTagName('li')
    for(var i=0; i<6; i++){
      !function(ii){
        liList[ii].onclick = function(){
          alert(ii) // 0、1、2、3、4、5
        }
      }(i)
    }
    

    相关文章

      网友评论

          本文标题:箭头函数和立即执行函数

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