What is `this` inside a new-invoked generator?
# André Bargull (10 years ago)
Question: what does the following code snippet log in the last line?
function* gen() { yield this; } let genObj = new gen(); let [_this] = genObj; console.log(_this === genObj); // ???
I’m finding three answers:
The spec says [1] that any reference to
this
in a generator invoked vianew
causes aReferenceError
.Firefox logs
false
for the code snippet.A year ago, Allen stated [2] that if you invoke a generator function via
new
,this
points to the generator object. On other words, the code snippet would logtrue
.
It's a ReferenceError. Future editions may add a meta property to make it possible to retrieve the current generator object (ecmascript#3626).
Question: what does the following code snippet log in the last line?
function* gen() { yield this; } let genObj = new gen(); let [_this] = genObj; console.log(_this === genObj); // ???
I’m finding three answers:
The spec says [1] that any reference to
this
in a generator invoked vianew
causes aReferenceError
.Firefox logs
false
for the code snippet.A year ago, Allen stated [2] that if you invoke a generator function via
new
,this
points to the generator object. On other words, the code snippet would logtrue
.[1] people.mozilla.org/~jorendorff/es6-draft.html#sec-generator-function-definitions-runtime-semantics-evaluatebody [2] esdiscuss.org/topic/reason-why-generators-do-not-have-references-to-themselves#content