一、函数的变化
1. 函数默认参数
function fn({a='0', b='1'} = {}) {
console.log(a, b);
};
fn(); //0 1
定义函数时可以给函数参数设置默认值,当调用函数时如果不传参或某个参数不传,那么函数的该参数就会设置成此默认值。
2. 函数参数默认已经定义了,不能再使用let、const在函数内去定义
function fn({a='0', b='1'} = {}) {
let a = 55; //Uncaught SyntaxError: Identifier 'a' has already been declared
console.log(a, b);
};
二、扩展运算符,rest运算符
基本样式:…
[1,2,3,4,5] => ...[1,2,3,4,5] => 1,2,3,4,5
1,2,3,4,5 => ...1,2,3,4,5 => [1,2,3,4,5]
案例说明:
let arr = ['apple', 'banana', 'orange'];
console.log(arr); //['apple', 'banana', 'orange']
console.log(...arr); //apple banana orange
function show(...a) {
console.log(a); //[1, 2, 3, 4, 5]
}
show(1,2,3,4,5);
function show1(a, b, c) {
console.log(a, b, c); //1 9 8
}
show1(...[1,9,8]);
function show2(a, b, ...c) {
console.log(a, b); //1 2
console.log(c); //[3,4,5]
}
show2(1,2,3,4,5);
三、箭头函数
=>
注意:
1. this问题,定义函数所在的对象,不在是运行时所在的对象
2. 箭头函数里面没有arguments,用’…'
function show() {
console.log(arguments); //输出arguments对象
}
let show = (...arguments) => {
console.log(arguments); //[1, 2, 3, 4]
}
show(1,2,3,4);
3. 箭头函数不能当构造函数
function show() {
this.name = 'abc'; //abc
}
let show = () => {
this.name = 'abc'; //index.html:21 Uncaught TypeError: show is not a constructor
}
let s = new show();
console.log(s.name);