函数新增特性
- 参数默认值
- rest参数
- 扩展运算符
- 箭头函数
- this绑定
- 尾调用
参数默认值
注意:默认值后面必须都是带默认值的变量
{
function test(x, y = 'world'){ // 默认值后面必须都是带默认值的变量
console.log('默认值',x,y);
}
test('hello'); // hello world
test('hello','kill'); // hello kill
}
参数默认值的作用域问题
{
let x='test';
function test2(x,y=x){
console.log('作用域',x,y);
}
test2('kill'); // kill kill
test2() // undefined undefined,形参x只声明未赋值
function testTwo(c,y=x){
console.log('作用域',c,y);
}
testTwo('kill') // kill test,这里取到外级作用域了
}
rest参数
{
function test3(...arg){ // ...把参数转成数组,和es5中的arguments相似,但不会有arguments[0]的问题
for(let v of arg){ // rest参数后不能有其他参数,会报错
console.log('rest',v);
}
}
test3(1,2,3,4,'a'); // 1 2 3 4 a
}
扩展运算符
rest 参数逆运算
{
console.log(...[1,2,4]); // 1 2 4,把数组转成离散的值
console.log('a',...[1,2,4]); // a 1 2 4
}
箭头函数
{
let arrow = v => v*2;
let arrow2 = () => 5;
console.log('arrow',arrow(3)); // 6
console.log(arrow2()); // 5
}
注意 this 绑定的问题
尾调用
尾调用,函数的最后一句话是函数
作用,提升性能
场景,函数嵌套时
{
function tail(x){
console.log('tail',x);
}
function fx(x){
return tail(x)
}
fx(123) // 123
}
网友评论