你不得不知道的箭头函数和普通函数使用区别!

前言

箭头函数是 ES6 新增的一种函数类型,它采用箭头 => 定义函数,也称为 lambda 函数。箭头函数语法更为简洁,用起来很是方便顺手。

但它存在一些需要注意的问题和局限性。在实际使用时,我们需要根据具体情况来选择合适的函数类型。

和普通函数的区别:this

箭头函数和普通函数最主要的区别在于它们对于 this 的处理方式不同。箭头函数不会改变 this 的指向,而是继承父级作用域的 this,而普通函数的 this 值则取决于它被调用时的运行环境。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <script>
        const obj = {
            name: 'John',
            getNameArrow: () => {
                console.log(this, this.name);
            },
            getNameFunc: function() {
                console.log(this.name);
            }
        }

        obj.getNameArrow();
        obj.getNameFunc();
    </script>
</body>
</html>

输出结果:

 可以看到,箭头函数在调用时继承父级作用域的 this 值,因此输出的是 Window和undefined;而普通函数则按照正常的作用域链查找方式,输出了正确的值。

箭头函数其他的特点

1.箭头函数没有自己的 arguments,只能通过继承父级作用域的 arguments 来获取传入的参数。

function myFunc() {
  const myArrow = () => console.log(arguments[0]);
  myArrow();
}

myFunc('Hello, world!'); // 输出 Hello, world!

2.箭头函数不能作为构造函数使用,因为它没有自己的 this,无法使用 new 关键字创建实例。

const MyObj = (name) => {
  this.name = name;
};

const obj = new MyObj('John'); // TypeError: MyObj is not a constructor

3.箭头函数不能使用 yield 关键字,因此无法用于生成器函数。

const gen = function* () {
  yield 1;
  yield 2;
  yield 3;
}

const arrowGen = () => {
  yield 1;
  yield 2;
  yield 3;
}

const myGen = gen();
const myArrowGen = arrowGen();

console.log(myGen.next()); // 输出 {value: 1, done: false}
console.log(myArrowGen.next()); // 抛出 SyntaxError 错误

4.箭头函数的语法更为简洁,适合用于定义单行的函数表达式。

const add = (a, b) => a + b; // 箭头函数语法更为简洁
const multiply = function (a, b) { return a * b; }; // 普通函数语法更为冗长

console.log(add(1, 2)); // 输出 3
console.log(multiply(2, 3)); // 输出 6

猜你喜欢

转载自blog.csdn.net/weixin_42373175/article/details/131324584