1.函數可以設置參數默認值
1 function test1(x,y=1){ 2 console.log(x,y) 3 } 4 test1(10)//10 1
2.rest參數:形式為...變量名
1 function test2(a,...b){ 2 for(let i of b){ 3 a+=i 4 } 5 console.log(a) 6 } 7 // 說明傳入的參數是一個一個的傳入,而不是數組形式 8 test2(100,1,2,3) //106 9 test2(100,[1,2,3,4])//1001,2,3,4
注意:如果有rest參數,那么它一定是最后一個參數
1 function test3(a,...b,c){}//Uncaught SyntaxError: Rest parameter must be last formal parameter
功能形如 “rest參數的逆運算”:
1 function test21(a,b){ 2 console.log(a+b) 3 } 4 // ...后面跟上數組好比是rest參數的逆運算 5 test21(...[1,2])//3
3.箭頭函數(=>)
例一:
1 var test4=v => v 2 // 相當於 3 // var test4=function (v){ 4 // return v 5 // } 6 console.log(test4(100))//100
例二:
1 var test5=()=>1 2 // 相當於 3 // var test5=function (){ 4 // return 1 5 // } 6 console.log(test5())//1
例三:
1 var test6=(num1,num2)=>num1*num2 2 // 相當於 3 // var test6=function (num1,num2){ 4 // return num1+num2 5 // } 6 console.log(test6(2,6))//12
注意:大括號被解釋成代碼塊,所以返回對象時要加上圓括號,否則報錯
1 // var test7=()=>{name:1,age:100}//報錯 2 var test7=()=>({name:1,age:100})//正確寫法 3 console.log(test7())//{name: 1, age: 100}
如果函數代碼塊內有
多條語句,用上大括號
1 var test8=(n1,n2)=>{return n1+n2} 2 console.log(test8(1,10))//11 3 var test9=(n1,n2)=>{ let a=n1*n2+n2*n2; console.log(a)} 4 test9(1,10)//110
重點!注意:箭頭函數中this指向的是定義時所在的對象,不同於普通函數this指向的是運行時所在對象
1 function Test10(){ 2 this.name='apple', 3 this.num=10, 4 setTimeout(()=>{ 5 //箭頭函數this始終指向定義時所在對象,即Test10 6 console.log('arrow function',this.num+1) 7 },1000); 8 setTimeout(function(){ 9 //普通函數在下面這種情況下,指向了全局對象window;嚴格模式下指向undefined 10 // 閉包 11 console.log('normal function',this.num+1) 12 },1000) 13 } 14 let te=new Test10() 15 //arrow function 11 16 //normal function NaN