What is the motivation of arrow functions in Javascript?

时间:2017-08-04 13:02:33

标签: javascript ecmascript-6 arrow-functions

I've been working in Javascript. Lately they've added arrow functions in ES6 which have benefits as

  1. Short Syntax
  2. Scope safety of this
  3. Clarity

However it has some disadvantage of using arrow function:

  1. It doesn't inherit the Function prototype
  2. We can't use it with callback function with dynamic context
  3. Can't be used as constructor

I want to ask following things:

  1. Why do they not inherit the Function prototype?
  2. Are they made to increase the usage functional programming in javascript? (motivation behind them)

I asked this because mdn page says that it doesn't have a prototype but doesn't explain why it doesn't have a prototype.

I read this series by Eric Elliot and I think we're moving on functional programming approach in javascript and due to planned releases, is there any chance that we can remove OOPS in this in near future?

2 个答案:

答案 0 :(得分:6)

It doesn't inherit the Function prototype

Of course they do.

Object.getPrototypeOf(() => {}) === Function.prototype

We can't use it with callback function with dynamic context and it can't be used as constructor

Yes, that follows logically from the lexical this scope.

Are they made to increase the usage functional programming in javascript?

No, they're made to simplify writing functions, e.g. callbacks. Of course that makes them also useful for functional programming, but I don't think that's the primary motivation. The lexical this is an explicit OOP feature.

答案 1 :(得分:0)

关于函数继承的语句是错误的,可能与它们don't have prototype property的事实相混淆。这是他们不能成为构造者这一事实的直接结果。一个不能用new构造对象的函数不需要prototype

他们是什么,没有自己的this上下文的功能,他们保持词汇this。它们不是键入function的简短方法。他们的潜在用例是各种需要保持上下文或根本不使用this的回调。如果箭头不适合这种情况,那么普通function就是这种情况。

ES2015箭头是从CoffeeScript借来的,他们长期以来证明了它们的实用性。