箭头函数 vs 粗箭头函数

20

我在互联网上找到了关于“箭头函数”和“胖箭头函数”的信息,但没有关于它们之间有何不同的信息。

它们之间是否有区别?

3个回答

34

这样的问题需要一点解释...

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 + '!';
};

CoffeeScript

当Jeremy Ashkenas引入CoffeeScript时,它带来了一些新的术语,特别是细箭头函数->)和胖箭头函数=>)。

一方面,细箭头函数是CoffeeScript中等价于ES5(匿名)函数表达式的形式。在CoffeeScript中,我们可以这样编写前面的示例:

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

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

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

另一方面,fat arrow function是CoffeeScript提供的一个很好的工具,在ES5中没有等效的语法。它的目的是更轻松地处理词法作用域,特别是当你想在回调函数中保留外部this时。让我们以CoffeeScript和传奇jQuery回调为例进行说明。假设我们在全局作用域中:

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

$(document).ready(function () {
  // Here "this" is "document"
  console.log(this);
});

如果我们想要在回调中操作外部的“this”,这是 ES5 代码:

var that = this;

$(document).ready(function () {
  console.log(that);
});

使用 CoffeeScript,可以使用 fat arrow function(胖箭头函数) 来替代:

// "this" is "window"!
$(document).ready => console.log this

当然,这不适用于细箭头函数

// "this" is "document"
$(document).ready -> console.log this

ECMAScript 6 (2015)

ES2015规范引入了箭头函数。它们是CoffeeScript中fat arrow functions的替代品。但由于ES6中没有thin arrow functions,因此在不使用CoffeeScript时谈论fat arrow functions并没有意义。在ES6中,您可以这样做:

// Here "this" is "window"
$(document).ready(() => console.log(this));

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

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

$(document).ready(function () {
  // Here "this" is "document"
  console.log(this);
});

8

有什么区别吗?

没有。

除了术语“fat arrow function”已被弃用和过时。

如果有人仍在使用CoffeeScript,则此答案不适用。


2
在CoffeeScript中,胖箭头函数会传递封装范围,而普通箭头则不会。

“传递封装范围”,这是什么意思? - a better oliver
看一下Badacadabra的回答,这就是我所说的例子。 - Mickers
他谈到了“this”。在作用域的组合中,“传递”没有意义。 - a better oliver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接