Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are generator methods constructors?

Methods when declared as methods (using ES6 enhanced object literals or classes) are not constructors / does NOT have a prototype chain.

But generators when declared via the method syntax, do have a prototype chain and are constructors.

Take the following example - (requires v8)

'use strict';
class x {
  *a() { this.b() }
  b() { print('class method'); }
}
let i = new x();
i.a.prototype.b = function() { print('generator method'); };
i.a().next();
(new i.a()).next();

Outputs,

class method
generator method

While adding prototypes to i.b, and calling new i.b() will throw an error because i.b is not a constructor, I'm able to do new i.a(), and this inside *a gets a different context.

  • Why does this difference exist?
  • What is the use case for having prototype in generators defined as methods?
like image 742
Boopathi Rajaa Avatar asked Aug 16 '15 20:08

Boopathi Rajaa


1 Answers

Definitely an odd quirk of the ES2015 spec. TC39 actually had a long discussion back in July, and decided to make generators non-newable.

The official change to the spec landed last month, and while there was a little concern about breaking things, V8 and SpiderMonkey implementors were in favor of going forward, so I would expect to see it stop working soon (and in fact, it already throws a TypeError in Firefox Nightly).

like image 98
dfreeman Avatar answered Sep 29 '22 07:09

dfreeman