函数参数的默认值

1
2
3
4
5
function fn(arg = 0) {
console.log(arg);
}
fn(); // 0
fn(100); // 100

与解构赋值配合使用

1
2
3
4
function fn([a, b = 0]) {
console.log(a + b);
}
fn([1]); // 1

函数参数的作用域

1
2
3
4
5
6
7
let v = 100;
function fn(arg = v) {
let v = 1000;
console.log(arg);
}

fn(); // 100

image-20201026151955312

rest参数

1
2
3
4
function fn(a, b, ...args) {
console.log(a, b, args);
}
fn(1, 2, 3, 4, 5); // 1 2 [ 3, 4, 5 ]

rest参数会将多余的参数放入到一个数组。

  • rest参数只能放在最后。
  • 函数的length属性不包含rest参数

箭头函数

基本语法

1
2
3
4
5
6
7
8
9
10
11
let fn1 = () => 2;
console.log(fn1()); // 2
let fn2 = (a, b) => a + b;
console.log(fn2(1, 2)); // 3
let fn3 = () => {
console.log("log");
return 1;
};
console.log(fn3());
// log
// 1

在ES5中,this取决于当前调用环境的上下文对象。而在ES6中,this取决于定义时的上下文对象。

注意事项

  1. 不能作为构造函数

    1
    2
    3
    4
    5
    6
    // 1. 不能作为构造函数
    var fn = () => {
    this.name = "张无忌";
    };
    var f = new fn();
    console.log(f);

    image-20201026154925977

  2. 可以作为对象的方法出现

    1
    2
    3
    4
    5
    6
    7
    let obj = {
    name: "张无忌",
    sayMe: () => {
    console.log("我是张无忌");
    },
    };
    obj.sayMe(); // 我是张无忌
  3. 箭头函数中不能使用arguments参数,需要使用rest参数代替

    image-20201026155331440

    1
    2
    3
    4
    var fn = (...args) => {
    console.log(args);
    };
    fn(1, 2, 3); //[ 1, 2, 3 ]

尾调用

1
2
3
4
5
6
7
8
function g(x) {
return x + 2;
}
function fn(x) {
return g(x); // 表示尾调用
}

console.log(fn(3)); // 5