This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
我通过使用Video tutorial学习Node js。我不明白Arrow函数的意义。常规函数和arrow函数之间的主要区别是什么?
enter image description here

最佳答案

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

范例1:

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


箭头函数不绑定到此,它们也不创建自己的此,因此使用了封闭此。

范例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,这使这些函数成为一线函数,如上面的示例所示。

09-25 17:44
查看更多