05. 箭头函数

2023-08-14 21:39:42发布
46

箭头函数的声明

let fn = (a, b) => {
    return a + b;
}

上面的代码等同于

var fn = function(a,b) {
    return a + b;
}


箭头函数和普通函数的区别

1. 箭头函数的this始终指向它最外层的函数

var name = 'marry';
const obj = {
    name: 'tom',
    say: function () {
        setTimeout(function () {
            console.log(this.name)
        }, 0);
    }
}
obj.say();

输出marry,如果改成用箭头函数

var name = 'marry';
const obj = {
    name: 'tom',
    say: function () {
        setTimeout(() => {
            console.log(this.name)
        }, 0);
    }
}
obj.say();

输出tom

2. 箭头函数不能作为构造函数实例化对象

const Person = (name, age) => {
    this.name = name;
    this.age = age;
}
const p = new Person('tom', 18);

运行后报错 :Uncaught TypeError: Person is not a constructor


3. 不能使用arguments变量

const fn = function () {
    console.log(arguments)
}
fn(1, 2, 3, 4, 5)

普通函数时可以的,输出 :

改成用箭头函数的话

const fn = () => {
    console.log(arguments)
}
fn(1, 2, 3, 4, 5)

则报错:Uncaught ReferenceError: arguments is not defined


箭头函数的简写

省略小括号

const fn = (n) => {
    console.log(n + n)
}
fn(3)

当函数只有一个参数的时候,小括号可以省略,上面的代码,你可以改成这样写 :

const fn = n => {
    console.log(n + n)
}
fn(3)

省略花括号

const fn = (n) => {
    return n + n;
}
fn(3)

当代码体只有一条语句时,花括号可以省略,上面的代码,你可以改成这样写:

const fn = (n) => n + n;
fn(3)

注意return也要去掉,上面的语句实际上还可以更简化,如 :

const fn = n => n + n;
fn(3)