ES6 箭头函数

2022-07-10  本文已影响0人  wulle__
普通函数:
    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(a);
    };

没有参数的时候 不能省略括号

    var fn5 = () => {
      console.log(123);
    };

返回值

    function aa() {
      // 正常函数
      return 123;
    }
命名函数转箭头函数
    let aa1 = () => 123;箭头函数
    // 箭头函数中,如果只有一条 return 语句,则可以省略 大括号
    // 如果 这个箭头函数 还有且只有一个形参
    // 则小括号也可以省略
    // let aa1 = a => a + 1;

    function b(){
        return function (a){
            return a+1
        }
    }
    let b=()=>a=>a+1;
    let b1=b()(1);
    console.log(b1); // 2
命名函数与箭头函数中this的指向问题
    btn.onclick=function(){
        console.log(this);// 标签
    }

    btn1.onclick=()=>{
        console.log(this);// window
    }

一般绑定事件函数的时候 不要使用 箭头函数

    btn.onclick=function(){
        setInterval(function(){
            console.log(this);// window
        },3000);
    }

    btn1.onclick=function(){
        setInterval(()=>{
            console.log(this);// 标签
        },3000);
    }

当内部函数使用箭头函数时,不会改变外部函数的 this指向

    btn.onclick=function(){
        btn1.onclick=function(){
            console.log(this);// btn1
        }
        btn1.onclick=()=>{
            console.log(this);// btn
        }
    }
总结
对象中的箭头函数

给对象定义方法时,不要使用箭头函数

    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);// obj
        }
        this.eat=()=>{
            console.log(this);// obj
        }
    }
    let d1=new Dog();
    d1.say();
    d1.eat();
上一篇 下一篇

猜你喜欢

热点阅读