箭頭函數和普通函數的區別


  // 普通函數
        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));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM