ES6函数变化
1.函数默认参数
function show ( { x= 0 , y= 0 } = { } ) {
console. log ( x, y)
}
show ( ) ;
2.函数参数默认是定义过的,不能再使用let, const声明,否则会报错
function show ( x= 10 ) {
let x = 20 ;
console. log ( x) ;
}
show ( ) ;
3.扩展运算符(...),可以将数组转化成普通的数字列表,反过来可以将数字列表转换成数组
let arr = [1,2,3];
console.log(...arr); // 1,2,3
function show(...a){
console.log(a); // [1,2,3]
}
show(1,2,3)
4.rest运算符(...) 三个点还可以叫剩余运算符,就是函数传递的参数,剩余未接收的值都由(...变量名) 这个变量接收
function show(a,b, ...c){ // 传递了5个值,只接收了两个,剩余的三个都由..c接收到了
console.log(a, b, c); // 1, 2, [3, 4, 5]
}
show(1, 2, 3, 4, 5);
5.箭头函数
() => 执行的语句
() => {
执行的语句
}
5.1、箭头函数中的this指向不再像ES5一样,谁调用this就指向谁,
ES6中的this指向,指向的是当前函数所在的对象.
5.2、箭头函数没有arguments,可以使用(...args)获取到,args这个名字可以随便定义
5.3、箭头函数不能当构造函数来使用
ES5 : function Show ( ) {
this . name = "yang" ;
}
let s = new Show ( ) ;
console. log ( s. name) ;
ES6 : let Show = ( ) => {
this . name = "yang" ;
}
let s = new Show ( ) ;
console. log ( s. name) ;