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

410 阅读2分钟

箭头函数是ES6引入的一种新的函数表示方式,相较于传统的函数,箭头函数更加简洁、易读。以下是箭头函数和普通函数的一些区别:

1. 箭头函数比普通函数更加简洁

箭头函数的语法更加紧凑,没有显式的function关键字,只需使用箭头(=>)将参数和函数体分隔开即可。例如:

// 普通函数
function sum(a, b) {
  return a + b;
}

// 箭头函数
const sum = (a, b) => a + b;

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

箭头函数不会创建自己的this,它只会在自己作用域的上一层继承this。所以箭头函数中this的指向在它在定义时已经确定了,之后不会改变。例如:

const obj = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  },
  greetArrow: () => {
    console.log(`Hello, my name is ${this.name}.`);
  },
};

obj.greet();  // 输出 "Hello, my name is Alice."
obj.greetArrow();  // 输出 "Hello, my name is undefined."

3. 箭头函数继承来的this指向永远不会改变

由于箭头函数不会创建自己的this,所以它继承来的this指向永远不会改变。例如:

const obj = {
  name: 'Alice',
  sayHello: function() {
    setTimeout(() => {
      console.log(`Hello, my name is ${this.name}.`);
    }, 1000);
  },
};

obj.sayHello();  // 输出 "Hello, my name is undefined.",因为箭头函数中的this指向全局对象Window,而不是obj

4. 箭头函数不能作为构造函数使用

箭头函数没有自己的this,且this指向外层的执行环境,因此不能作为构造函数使用。例如:

const Person = () => {
  this.name = 'Alice';
};

const alice = new Person();  // 报错: Person is not a constructor

5. 箭头函数没有自己的arguments

箭头函数没有自己的arguments对象。在箭头函数中访问arguments实际上获得的是它外层函数的arguments值。例如:

function sum(...nums) {
  return nums.reduce((total, num) => total + num, 0);
}

const sumArrow = (...nums) => nums.reduce((total, num) => total + num, 0);

console.log(sum(1, 2, 3));  // 输出 6
console.log(sumArrow(1, 2, 3));  // 输出 6
const sumArrow = (...args) => args.reduce((acc, val) => acc + val, 0);

6. 箭头函数没有prototype

箭头函数没有prototype属性,因此无法通过原型链访问箭头函数的属性或方法。

7. 箭头函数的this指向哪里?

箭头函数的this指向其所在上下文的this值。例如:

const obj = {
  name: 'Alice',
  greet: function() {
    setTimeout(() => {
      console.log(`Hello, my name is ${this.name}.`);
    }, 1000);
  },
};

obj.greet();  // 输出 "Hello, my name is Alice."

注意

  • 箭头函数没有prototype(原型),所以箭头函数本身没有this 箭头函数的this在定义的时候继承自外层第一个普通函数的this。

  • 如果箭头函数外层没有普通函数,严格模式和非严格模式下它的this都会指向window(全局对象) 箭头函数本身的this指向不能改变,但可以修改它要继承的对象的this。

结论:选择合适的函数类型

在选择使用箭头函数还是普通函数时,考虑以下几个方面:

  • 简洁性需求:对于简单的操作和不需要动态 this 的场景,箭头函数是理想的选择。
  • 动态 this 绑定:如果函数的行为取决于调用时的 this,应选择普通函数。
  • 构造函数需求:需要实例化对象时,只能使用普通函数。

了解箭头函数与普通函数的特性,可以使你在实际编程中做出更合适的选择,从而写出更加优雅和高效的代码。