ES6-函数

作者: div式人格 | 来源:发表于2022-06-20 09:24 被阅读0次

    1. 函数的声明

    • ES6 允许使用“箭头”(=>)定义函数。
    • 箭头函数只有一个参数时,可以省略括号。
      // 普通函数
      function fn1(a) {    // 命名函数
           console.log(a);
      }
      var fn2 = function (a) {    // 字面量形式
            console.log(a);
      }
    
      // 箭头函数 
      var fn3 = (a,b) => {   // 多个参数
            console.log(a,b);
      }
      fn3(10,11);
      var fn4 = a => {      //  一个参数,可以省略括号。
         // console.log(this);
         console.log(a);
      }
      fn4(10);
    

    2. 带返回值的箭头函数

    • 箭头函数中 如果只有一条 return 语句 则可以省略大括号。
    • 如果这个箭头函数 还有且只有一个参数,则小括号也可以省略
      function a1(){      // 普通函数
            return 123;
      }
     let a2 = () => 123;  // 箭头函数
    
      function b1() {
            return function (a) {
                return a + 1;
            }
        }
     let b2 = () => a => a + 1;
     let b3 = b1()(10);
     console.log(b3);
    

    3. 箭头函数的指针 this

    • 一般绑定事件函数时,不要绑定箭头函数。
    • 当内部函数使用箭头函数时,不会改变外部函数的 this 指向。
        btn1.onclick = function(){
            console.log(this);       // 当前DOM元素: button标签
            setInterval(function(){
                console.log(this);   // window 对象
            },3000);
        }
        btn2.onclick = function() {
            console.log(this);       // DOM元素 btn2标签   
            setInterval(() => {
                console.log(this);   // DOM元素 btn2标签   
            },3000);
        }
    
        btn1.onclick = function(){
            // btn2.onclick = function(){
            //     console.log(this);   // DOM元素 btn2标签   
            // }
            btn2.onclick = () => {
                console.log(this);      // DOM元素 btn1标签   
            }
        }
      
        let obj = {
            say : function(){
                console.log(this);  // obj
            },
            eat : ()=>{
                console.log(this);  // window对象
            }
        }
        obj.say();
        obj.eat();
    
      // 给对象定义方法时
      function Dog(){
           this.say = function(){
              console.log(this);
           }
           this.eat = () => {
               console.log(this);
           }
        }
        let d1 = new Dog();
        d1.say();
        d1.eat();
    
    
    
    总结:
    • 普通函数: 谁调用我 我的this指向谁
    • 箭头函数: 在被定义时,定义的环境的this就指向谁, 我就指向谁。

    相关文章

      网友评论

        本文标题:ES6-函数

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