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