Reputation: 231
I have two questions First : I recently learnt that in ES 6 derived class, if super() is not called, the "this" is not available. I understand why it is done this way, but I want to know conceptually, what piece of ES6 compiled code is making "this" to be unavailable. I mean if i want to do the same in ES5 to make "this" unavailable, how can that be done.
Second: Why are we not able to instantiate ES6 prototype methods Below will not work-
class abc{
func(){}
}
var a = new abc()
var b = new a.func()
whereas this will work-
function abc(){}
abc.prototype.func = function(){}
var a = new abc()
var b = new a.func()
WHY ? For the above question as well, I want to know more about what implementation is doing this and not why they decided to provide this feature.
Upvotes: 1
Views: 648
Reputation: 664346
I mean if i want to do the same in ES5 to make "this" unavailable, how can that be done.
It's not possible. This behaviour is new in ES6 (and really hard to transpile).
Why are we not able to instantiate ES6 prototype methods Below will not work
Because method definitions, similar to arrow functions, are no constructors. Unlike function
expression that can be both called and constructed.
Upvotes: 4
Reputation: 14423
ES6 classes that use extend instantiate objects kind of in a different way from constructors.
When you do new something()
for constructors, there's a new object instantiated and available through this
. While ES6 classes that extend other classes will go up the chain and instantiate the base object, thanks to super()
.
In other words:
class C extends B {}
class B extends A {}
class A {}
new C();
Will actually travel all the way to A and see that's not a class that uses extend and will instantiate that one (with a twist, the prototype of the object will be the prototype of the C
). super
calls on C and B will set the this
to whatever super returned.
This is why this
is never set before super()
because classes that extend something will not create a new object by themselves.
Regarding point 2, the class elements are methods (which can't be constructed), whereas functions on the prototype of constructors are normal functions that work as constructors.
Upvotes: 1