ES6 之箭头函数 && 普通函数的 10 个区别

发布于 2021-08-03  335 次阅读


1.箭头函数没有 prototype 属性

let fn = () => {};
console.log(fn.prototype === undefined); //true

2.箭头函数的 this 指向定义时外层第一个普通函数的 this

let fn,
    barObj = { message: 111 },
    fooObj = { message: 222 };
function bar() {
    // 运行时实例
    fn();
}
function foo() {
    // 定义时实例
    fn = () => {
        console.log("输出:", this); // 输出: {message: 222}
    };
}
// 这里有一个问题就是,foo.call一定要在bar.call之前,大家想想为什么呢?
foo.call(fooObj);
bar.call(barObj);

3.不能直接修改箭头函数的 this

let fn,
    barObj = { message: 111 },
    fooObj = { message: 222 };
function bar() {
    // 运行时实例
    fn.call({ message: 333 });
    baz.call({ message: 333 });
}
function foo() {
    // 定义时实例
    fn = () => {
        console.log("输出:", this); // 输出: {message: 222}
    };
}
function baz() {
    console.log("输出:", this); // 输出: {message: 333}
}
foo.call(fooObj);
bar.call(barObj);
// 这里如何能修改箭头函数this的指向了,我们可以间接操作。
// 修改箭头函数的this指向定义时外层第一个普通函数的this,来达到我们的目的

4.当箭头函数外层没有普通函数时,它的 this 在严格和非严格模式都是指向 window

let foo = () => {
    console.log("输出:", this); //Window
};
foo();

let coo = function () {
    console.log("输出:", this); //Window
};
coo();
"use strict";
let foo = () => {
    console.log("输出:", this); //Window
};
foo();

let coo = function () {
    console.log("输出:", this); //undefined
};
coo();

5.箭头函数没有外层函数直接使用 arguments 会报错

let foo = () => {
    console.log("输出:", arguments); //arguments is not defined
};
foo();

6.箭头函数有外层函数时,arguments 继承自外层函数的 arguments

function foo() {
    console.log(arguments);
    function boo() {
        console.log(arguments);
        function coo() {
            console.log(arguments);
            let aoo = () => {
                console.log(arguments);
            };
            aoo("外层4");
        }
        coo("最外层3");
    }
    boo("外层2");
}
foo("外层1");

file

7.使用 new 调用箭头函数会报错

let aoo = () => {
    console.log(arguments); //aoo is not constructor
};
let boo = new aoo();

8.箭头函数没有外层函数时,new.target 会报错

let a = () => {
    console.log(new.target); //new.target expressin is not allowed here
};
a();

9.箭头函数不支持重名参数

function foo(a, a) {
    console.log(a, arguments); //Duplicate parameter name not allowed in this context
}
var boo = (a, a) => {
    console.log(a);
};
foo(1, 2);
boo(1, 2);

10.箭头函数语法更具优雅

  • 箭头函数不用写function;
  • 箭头函数只有一个参数时,可以省略括号;
  • 箭头函数可以省略{}和return。

总结

  1. 普通函数和箭头函数的区别:
  2. 箭头函数没有 prototype(原型),所以箭头函数本身没有 this;
  3. 箭头函数的 this 在定义的时候继承自外层第一个普通函数的 this;
  4. 如果箭头函数外层没有普通函数,严格模式和非严格模式下它的 this 都会指向 window(全局对象);
  5. 箭头函数本身的 this 指向不能改变,但可以修改它要继承的对象的 this;
  6. 箭头函数的 this 指向全局,使用 arguments 会报未声明的错误;
  7. 箭头函数的 this 指向普通函数时,它的 argumens 继承于该普通函数;
  8. 使用 new 调用箭头函数会报错,因为箭头函数没有 constructor;
  9. 箭头函数不支持 new.target;
  10. 箭头函数不支持重命名函数参数,普通函数的函数参数支持重命名;
  11. 箭头函数相对于普通函数语法更简洁优雅。

注意事项:

  • 箭头函数一条语句返回对象字面量,需要加括号;
  • 箭头函数在参数和箭头之间不能换行;
  • 箭头函数的解析顺序相对 || 靠前。

不适用场景:

箭头函数的this意外指向和代码的可读性。


博主好穷啊,快点支助一下吧 ε = = (づ′▽`)づ