箭头功能与胖箭头功能

Sam*_*ack 15 javascript ecmascript-6 arrow-functions

我在互联网上找到了关于名称,箭头功能胖箭头功能的信息,但没有关于它们之间有什么不同的信息.

有什么不同吗?

Bad*_*bra 24

这个问题需要一些解释......

ECMAScript 5

在ES5规范中,根本没有箭头功能.那么通常使用传统的函数表达式如下:

// Example n°1
var myFunction = function () {
  return 'Hello!';
};

// Example n°2
var obj = {
  myFunction: function () {
    return 'Hello!';
  }
};

// Example n°3
var arr = ['foo', 'bar'];
arr.map(function (item) {
  return 'Hello, ' + item + '!';
};
Run Code Online (Sandbox Code Playgroud)

CoffeeScript的

当Jeremy Ashkenas介绍CoffeeScript时,它带来了一个新的术语,特别是瘦箭头函数(->)和胖箭头函数(=>).

一方面,细箭头函数是与ES5(匿名)函数表达式等效的CoffeeScript.在CoffeeScript中,我们可以编写前面的示例,如下所示:

# Example n°1
myFunction = -> 'Hello!'

# Example n°2
obj =
  myFunction: -> 'Hello!'

# Example n°3
arr = ['foo', 'bar']
arr.map((item) -> "Hello, #{item}!")
Run Code Online (Sandbox Code Playgroud)

另一方面,胖箭头函数是CoffeeScript提供的一个很好的实用工具,它在ES5中没有相同的语法.其目的是与词法范围更容易发挥,尤其是当你要保持外在回调.让我们以CoffeeScript和传奇的jQuery回调为例.假设我们处于全球范围:

// Here "this" is "window"
console.log(this);

$(document).ready(function () {
  // Here "this" is "document"
  console.log(this);
});
Run Code Online (Sandbox Code Playgroud)

如果我们想在回调中操纵外部"this",这里是ES5代码:

var that = this;

$(document).ready(function () {
  console.log(that);
});
Run Code Online (Sandbox Code Playgroud)

使用CoffeeScript,可以使用胖箭头功能:

// "this" is "window"!
$(document).ready => console.log this
Run Code Online (Sandbox Code Playgroud)

当然,它不适用于细箭头功能:

// "this" is "document"
$(document).ready -> console.log this
Run Code Online (Sandbox Code Playgroud)

ECMAScript 6(2015)

ES2015规范引入了箭头功能.它们是CoffeeScript中胖箭头函数的替代品.但由于ES6 中没有精简箭头功能,因此在不使用CoffeeScript时没有理由讨论胖箭头功能.在ES6中,您可以这样做:

// Here "this" is "window"
$(document).ready(() => console.log(this));
Run Code Online (Sandbox Code Playgroud)

现在,如果要保留词法作用域的正常行为,只需使用ES5语法:

$(document).ready(function () {
  // Here "this" is "document"
  console.log(this);
});
Run Code Online (Sandbox Code Playgroud)


小智 6

有什么不同吗?

没有.

除了"胖箭头功能"一词已被弃用和过时.

这个答案不适用于CoffeeScript,以防任何人仍在使用它.