2

Is it possible to declare an anonymous generator function using the arrow syntax in ES6 JavaScript? This is what I've tried:

let func = *() => { };

but this doesn't parse (I'm using Babel.js to compile my ES6 to ES5). The documentation on MDN only mentions the more standard syntax:

let func = function *() { };

I'd like to be able to define the generator function using a arrow in order to take advantage of the lexical scoping of this. Is this possible?

Mulan
  • 129,518
  • 31
  • 228
  • 259
Nathan Friend
  • 12,155
  • 10
  • 75
  • 125
  • 2
    You can't use fat-arrows for generators. See http://stackoverflow.com/questions/27661306/can-i-use-es6s-fat-arrow-notation-with-generators-node. BTW, it's more common to refer to these as "fat-arrow functions" than "lambdas". –  May 19 '15 at 02:26
  • Your terminology is odd. `function*() {}` is a "lambda" as well (in the form of a function expression). – Bergi May 19 '15 at 02:40
  • What are you trying to do that would necessitate a lexically-scoped `this` in a generator function? – Bergi May 19 '15 at 02:42
  • Thanks @Bergi - I've edited the question to use "fat arrow" instead of "lambda". I'm converting a standard self-executing function into a self-executing generator function, and I'll need to access class properties inside the generator function. I think I've found a way to get the same effect using `.apply()`: `yield* (function *() { }).apply(this)` – Nathan Friend May 19 '15 at 02:55
  • Why would one ever immediately-execute a generator function? If you are going for ES6, use blocks to scope variables. `{ let …; yield…;}`, not `yield* …`. – Bergi May 19 '15 at 02:59
  • Normally, you wouldn't. In my case, I'm writing a [Cool](http://en.wikipedia.org/wiki/Cool_(programming_language)) to JavaScript compiler. In Cool, *all* expressions return a value, so I use self-executing functions to wrap expressions that don't return a value naturally in JavaScript (i.e. if/then/else expressions). Also, Cool allows for synchronous user input, which I'm achieving using generators. So not at all your normal use case. – Nathan Friend May 19 '15 at 03:06

0 Answers0