In a child class (that extends from a parent), if you try to access this
before super()
is called, iojs will throw an error: ReferenceError: this is not defined
. Meaning we can't manipulate our child object in its own constructor before the parent constructor is run.
class A {
constructor(value) { this.value = value; }
setPoint(x, y) { this.x = x; this.y = y; }
}
class B extends A {
constructor(x, y) {
this.setPoint(x, y);
super('from parent');
}
}
let b = new B(1, 2); // throws error
I don't believe this is intended behaviour, seeing as:
function B(x, y) {
this.setPoint(x, y)
A.call(this, 'from parent');
}
B.prototype = Object.create(A.prototype);
Is perfectly valid in ES5 and to my understanding, should be what's happening under the hood.
Any clarification would be great. :)
That is V8 related, we have no control over that. Also, I may be wrong, but I believe that is the intended functionality. Allowing instance manipulation before calling super()
could result in unexpected behaviour from the super class applied constructor.
@domenic would know better.
Cool, any ref to the ES6 class spec in this regard? (no pun intended)
Yes, this is part of the ES2015 spec. I don't really have time to go research this for you but you should be able to find it yourself.
This is very much intended behavior and ES2015 is different from ES5 in that respect. The ES5 translation you give is not accurate; it does not reflect what is going on under the hood. There have been several recent es-discuss threads about this as well if you care to find those.
Yep, I downloaded the most recent draft of the spec and I'll look it over. :) Maybe this suggestion belongs as a v8 issue instead, but I'm thinking the error could the error be a little more explicit - ReferenceError: this is not defined
is pretty confusing. Most of the new errors I'm seeing revolving around use of super (super not expected here
etc.) are pretty clear, but this one threw me for a bit of a loop.
Thanks guys!
the same code in window have this porblem, but in mac or linux have no error...
Closing, working as intended.
@binlaniua What do you mean?
Can you post the code sample and the output of the same version running on various platforms?
@keithwhor Did you find the location of this in the spec?
You need to call super before referencing this
. Until you call super
, this
is undefined. See: http://stackoverflow.com/q/32516204/1157054
Most helpful comment
That is V8 related, we have no control over that. Also, I may be wrong, but I believe that is the intended functionality. Allowing instance manipulation before calling
super()
could result in unexpected behaviour from the super class applied constructor.@domenic would know better.