node.js - NodeJS 中的常规函数​​和箭头函数有什么区别?

标签 node.js arrow-functions

我使用视频教程学习 Node js。我不明白箭头函数的要点。常规函数和箭头函数之间的主要区别是什么? enter image description here

最佳答案

箭头函数是 ES6 中引入的一种更简洁的函数编写方式。 箭头函数是匿名函数,这意味着您无法命名它。

示例1:

  var addRegular = function(x, y)  { return x + y };
  var addArrow = (x, y) =>  x + y;

箭头函数不会绑定(bind)到 this,它们不会创建自己的 this,因此正在使用封闭的 this。

示例2:

//1. regular function, creates own scope 
function Counter() {
  //set count to 0
  this.count = 0;
  var setOne  = function () {
    this.count = 1;
  };
  setOne(); 
}
var c = new Counter();
console.log(c.count);// outer count will stay unchanged.

//2. arrow function, uses outer this
function Counter() {
  this.count = 0;
  var setTwo = () => {this.count = 2};
  setTwo();
}
var c = new Counter();
console.log(c.count);//will be equal 2.

箭头函数有一个隐式返回值,这意味着不需要编写 return,这使得这些函数可以单行执行,如上面的示例所示。

关于node.js - NodeJS 中的常规函数​​和箭头函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861157/

相关文章:

node.js - lodash isNil 不是一个函数

node.js - 在 NodeJS 中访问 AWS SSM 参数

mysql - DigitalOcean 上的 NodeJs 无法连接到 Amazon RDS 上的 MySQL 数据库

reactjs - 将代码从使用 .bind(this) 转换为箭头函数

reactjs - 不使用箭头函数将参数传递给 prop 函数

Node.js + Bluebird + csv : extra item [object Object]

node.js - Sequelize查询执行顺序错误

javascript - 期望返回箭头中的值;函数数组回调返回。为什么?

javascript - 如何在不重新绑定(bind) this 的情况下返回带有粗箭头函数的对象?

javascript - 来自箭头函数的 ES6 removeEventListener (OOP)