@Bergi mentioned new.target.prototype
, but I was looking for a concrete example proving that you can access this
(or better, the reference to the object the client code is creating with new
, see below) without having to call super()
at all.
Talk is cheap, show me the code... So here is an example:
class A { // Parent
constructor() {
this.a = 123;
}
parentMethod() {
console.log("parentMethod()");
}
}
class B extends A { // Child
constructor() {
var obj = Object.create(new.target.prototype)
// You can interact with obj, which is effectively your `this` here, before returning
// it to the caller.
return obj;
}
childMethod(obj) {
console.log('childMethod()');
console.log('this === obj ?', this === obj)
console.log('obj instanceof A ?', obj instanceof A);
console.log('obj instanceof B ?', obj instanceof B);
}
}
b = new B()
b.parentMethod()
b.childMethod(b)
Which will output:
parentMethod()
childMethod()
this === obj ? true
obj instanceof A ? true
obj instanceof B ? true
So you can see that we are effectively creating an object of type B
(the child class) which is also an object of type A
(its parent class) and within the childMethod()
of child B
we have this
pointing to the object obj
which we created in B's constructor
with Object.create(new.target.prototype)
.
And all this without caring about super
at all.
This leverages the fact that in JS a constructor
can return a completely different object when the client code constructs a new instance with new
.
Hope this helps someone.