js中箭头函数与普通函数的区别

箭头函数(Arrow Function)和普通函数(普通的function声明)在JavaScript中有一些重要的区别。以下是箭头函数和普通函数的主要区别:

  1. 语法:箭头函数的语法更简洁。

普通函数:

function add(a, b) {
    
    
  return a + b;
}

箭头函数:

const add = (a, b) => a + b;
  1. this绑定:箭头函数不会创建自己的this值,而是从作用域链的上一层继承this值。

普通函数:

function Person() {
    
    
  this.age = 0;

  setInterval(function growUp() {
    
    
    this.age++; // 这里的this指向全局对象(在浏览器中是window)
  }, 1000);
}

const p = new Person();

箭头函数:

function Person() {
    
    
  this.age = 0;

  setInterval(() => {
    
    
    this.age++; // 这里的this指向Person实例对象
  }, 1000);
}

const p = new Person();
  1. arguments对象:箭头函数没有自己的arguments对象,而是继承自外层函数的arguments。

普通函数:

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

console.log(sum(1, 2, 3, 4)); // 10

箭头函数:

const sum = () => {
    
    
  return Array.from(arguments).reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 抛出错误:arguments is not defined
  1. 不能作为构造函数:箭头函数不能作为构造函数,不能使用new关键字。

普通函数:

function Person(name) {
    
    
  this.name = name;
}

const p = new Person('Tom');
console.log(p.name); // Tom

箭头函数:

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

const p = new Person('Tom'); // 抛出错误:Person is not a constructor
  1. 没有prototype属性:箭头函数没有prototype属性,因为它们不能作为构造函数。

普通函数:

function Person() {
    
    }

console.log(Person.prototype); // 输出:{constructor: ƒ}

箭头函数:

const Person = () => {
    
    }

console.log(Person.prototype); // 输出:undefined

总结:箭头函数和普通函数在语法、this绑定、arguments对象、构造函数和prototype属性方面有很大区别。在编写代码时,需要根据实际需求选择使用哪种函数。

猜你喜欢

转载自blog.csdn.net/lalala8866/article/details/142384280