我在互联网上发现了两个名字,箭头函数和fat箭头函数,但是没有关于它们之间有什么不同的信息。
有什么不同吗?
发布于 2017-04-24 16:41:50
这样的问题需要一些解释..。
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 )引入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箭头函数是CoffeeScript提供的一个很好的实用工具,在ES5中没有相同的语法。它的目的是更容易地使用词法作用域,特别是当您希望将外部(这个)保持在回调中时。让我们以一个通用的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箭头函数来代替:
// "this" is "window"!
$(document).ready => console.log this当然,它不适用于细箭头函数。
// "this" is "document"
$(document).ready -> console.log thisECMAScript 6(2015年)
ES2015规范引入了箭头函数。它们是CoffeeScript中fat箭头函数的替代方案。但是,由于ES6中没有细箭头函数,所以没有理由在不使用CoffeeScript时讨论胖箭头函数。在ES6中,您可以这样做:
// Here "this" is "window"
$(document).ready(() => console.log(this));现在,如果要保留词法作用域的正常行为,只需使用ES5语法:
$(document).ready(function () {
// Here "this" is "document"
console.log(this);
});发布于 2017-04-24 13:20:03
有什么不同吗?
No.
但“胖箭头功能”这个词已经过时了。
这个答案不适用于CoffeeScript,以防有人还在使用它。
发布于 2017-04-24 13:01:56
在CoffeeScript中,fat箭头函数通过封装作用域,而普通箭头不传递。
https://stackoverflow.com/questions/43588722
复制相似问题