javascript - Why are generator methods constructors? -
methods when declared methods (using es6 enhanced object literals or classes) not constructors / not have prototype chain.
but generators when declared via method syntax, have prototype chain , constructors.
take following example - (requires v8)
'use strict'; class x { *a() { this.b() } b() { print('class method'); } } let = 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 i.b
, , calling new i.b()
throw error because i.b
not constructor, i'm able new i.a()
, , this
inside *a
gets different context.
- why difference exist?
- what use case having prototype in generators defined methods?
definitely odd quirk of es2015 spec. tc39 had long discussion back in july, , decided make generators non-new
able.
the official change spec landed last month, , while there little concern breaking things, v8 , spidermonkey implementors in favor of going forward, expect see stop working (and in fact, throws typeerror
in firefox nightly).
Comments
Post a Comment