箭头函数

97 阅读1分钟

1. 箭头函数

// 传统函数表达式 
const add = function(x, y) { return x + y; }; 
// 箭头函数 
const add = (x, y) => x + y; 
// 无参数的箭头函数 
const greet = () => "Hello, World!";

2. 箭头函数没有arguments

  • arguments 用来保存函数的实参
const fn = function () {
    console.log(arguments); // Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
    console.log(arguments instanceof Array); // false
}
fn()

const fn2 = (...arg) => {
    console.log(arg);// []
    console.log(arg instanceof Array); // true
    console.log(arguments); // arguments is not defined
}
fn2()

3. 箭头函数没有自己的this

  • 箭头函数的 this 值是在创建函数时继承自外部作用域,而不是在运行时确定。
const fn = function () {
    console.log(this); // window
}
fn()

const fn2 = () => {
    console.log(this); // window
}
fn2()
// 对象里面没有作用域
const obj={
    hello:()=>{
        console.log(this);
    }
}
obj.hello() // window


const obj2 = {
    hello: function () {
        const test = () => {
            console.log(this);
        }
        test()
    }
}
obj2.hello() // {hello: ƒ}

const test3 = obj2.hello
test3() // window

4. 箭头函数中的this无法通过call()、apply、bind()修改

5. 箭头函数无法作为构造函数使用

6. 优先使用箭头函数