箭头函数和普通函数的区别

  // 普通函数
        function f1(){
            console.log("我是普通函数"); 
        }
        f1()
 
  // 箭头函数: 箭头函数相当于匿名函数,如果没有参数,就只写一个(),有参数直接写在(参数1,参数2)
        let f2 = () =>console.log("ddd");// 如果函数里面只有一个表达式,可以省略{}和return
        f2()
        let f3 = ()=>{                   // 如果有多个表达式则不能省略{}和return
            console.log("我是箭头函数");
            f1()
        }
        f3()
 
 
    // 区别1.箭头函数是匿名函数,所以不能作为构造函数,因此也不能使用new
    let func = () =>{
        console.log("6666");      
    }
    let newfunc = new func() //会报错; Uncaught TypeError: func is not a constructor

    // 区别2.箭头函数不绑定arguments,取而代之的是用rest参数解决
    function f4(a){  // 普通函数
        console.log(arguments); 
        console.log(arguments.length); // length指向传入当前函数参数的长度    
    }
    var a = [2,3,5,6,87]  
    f4(a)  // Arguments [Array(5), callee: ƒ, Symbol(Symbol.iterator): ƒ]


    let f5= (a) =>{  // 箭头函数
        console.log(arguments);  
    }
    f5(3,4,5,78,5) // 会报错;Uncaught ReferenceError: arguments is not defined 


    let f6 = (...a)=>{
        console.log(a);  
    }
    f6(3,45,6,7,8) // 输出 3,45,6,7,8

    // 区别3.箭头函数不绑定this,但会捕获上下文的this   ,作为自己的this
    var b = 100
    var obj ={
        a:10,
        b:function(){
            console.log(this.a);//输出:10;普通函数中的this指向的是调用该函数的对象
            console.log(this); // {a: 10, b: ƒ, c: ƒ}  
        },
        c:()=>{
            console.log(this.a); // 箭头函数中没有this,但是引用了调用该函数对象外部代码块的this指向,所以输出的是undifined
            console.log(this.b); // 输出 10 
        }
    }
    obj.b()
    obj.c()
 
 var obj2 = {
            a: 10,
            b: function () {
                console.log(this.a); //10
            },
            c: function () {
                return () => {
                    console.log(this.a); //10 此时调用改函数的是外层的这个函数,所以引用的是外层的obj2这个对象,this也就指向这个对象了
                }
            }
        }
        obj2.b();
        obj2.c()();
 
// 区别4.箭头函数通过 call()  或   apply() 方法调用一个函数时,只传入了一个参数,对 this 并没有影响。
        let obj3 = {
            a: 10,
            b: function (n) {
                let f = (n) =>n + this.a
                return f(n)
            },
            c:function(n){
                let f = (n,m) => n+this.a
                let m={
                    a:20
                }
                return f.call(m,n)
            }
        }
        console.log(obj3.b(1));
        console.log(obj3.c(1));
posted @ 2019-10-31 17:05  天天向上啊  阅读(2048)  评论(0编辑  收藏  举报