es6(三):es6中函数的扩展(参数默认值、rest参数、箭头函数)

时间:2023-03-10 05:11:10
es6(三):es6中函数的扩展(参数默认值、rest参数、箭头函数)

1.函数可以设置参数默认值

 function test1(x,y=1){
console.log(x,y)
}
test1(10)//10 1

2.rest参数:形式为...变量名

 function test2(a,...b){
for(let i of b){
a+=i
}
console.log(a)
}
// 说明传入的参数是一个一个的传入,而不是数组形式
test2(100,1,2,3) //
test2(100,[1,2,3,4])//1001,2,3,4

注意:如果有rest参数,那么它一定是最后一个参数

 function test3(a,...b,c){}//Uncaught SyntaxError: Rest parameter must be last formal parameter

功能形如 “rest参数的逆运算”:

 function test21(a,b){
console.log(a+b)
}
// ...后面跟上数组好比是rest参数的逆运算
test21(...[1,2])//

3.箭头函数(=>)

例一:

 var test4=v => v
// 相当于
// var test4=function (v){
// return v
// }
console.log(test4(100))//

例二:

 var test5=()=>1
// 相当于
// var test5=function (){
// return 1
// }
console.log(test5())//

例三:

 var test6=(num1,num2)=>num1*num2
// 相当于
// var test6=function (num1,num2){
// return num1+num2
// }
console.log(test6(2,6))//

注意:大括号被解释成代码块,所以返回对象时要加上圆括号,否则报错

 // var test7=()=>{name:1,age:100}//报错
var test7=()=>({name:1,age:100})//正确写法
console.log(test7())//{name: 1, age: 100}
如果函数代码块内有多条语句,用上大括号
 var test8=(n1,n2)=>{return n1+n2}
console.log(test8(1,10))//
var test9=(n1,n2)=>{ let a=n1*n2+n2*n2; console.log(a)}
test9(1,10)//

重点!注意:箭头函数中this指向的是定义时所在的对象,不同于普通函数this指向的是运行时所在对象

 function Test10(){
this.name='apple',
this.num=10,
setTimeout(()=>{
//箭头函数this始终指向定义时所在对象,即Test10
console.log('arrow function',this.num+1)
},1000);
setTimeout(function(){
//普通函数在下面这种情况下,指向了全局对象window;严格模式下指向undefined
// 闭包
console.log('normal function',this.num+1)
},1000)
}
let te=new Test10()
//arrow function 11
//normal function NaN