“箭头功能”和“功能”是否等效/可互换?

JavaScript

Harry逆天Eva

2020-03-12

ES2015中的箭头函数提供了更简洁的语法。

  • 我现在可以用箭头函数替换所有函数声明/表达式吗?
  • 我要注意什么?

例子:

构造函数

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

// vs

const User = name => {
  this.name = name;
};

原型方法

User.prototype.getName = function() {
  return this.name;
};

// vs

User.prototype.getName = () => this.name;

对象(文字)方法

const obj = {
  getName: function() {
    // ...
  }
};

// vs

const obj = {
  getName: () => {
    // ...
  }
};

回呼

setTimeout(function() {
  // ...
}, 500);

// vs

setTimeout(() => {
  // ...
}, 500);

可变函数

function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// vs
const sum = (...args) => {
  // ...
};

第1280篇《“箭头功能”和“功能”是否等效/可互换?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android