this
isn't either Base
or Derived
in your examples. It's an instance of Base
and (where you use new Derived
) also an instance of Derived
.
When you do new Derived
, this
is created as an instance of Derived
. It doesn't matter whether you look at it in the Base
constructor or the Derived
constructor, in both cases this
refers to the single object created by using new
(which is an instance of both Base
and Derived
).
Here's some other logging that may be more useful:
class Base {
constructor() {
console.log(
"In Base: ",
this instanceof Base,
this instanceof Derived,
this.constructor.name
);
}
}
class Derived extends Base {
constructor() {
super();
console.log(
"In Derived:",
this instanceof Base,
this instanceof Derived,
this.constructor.name
);
}
}
new Derived();
// =>
// In Base: true true Derived
// In Derived: true true Derived
We can go further to prove it's the same object (you wouldn't store the value of this
on a global variable in real code, but this is to see what's going on in this specific example):
let thisInBase;
class Base {
constructor() {
thisInBase = this;
console.log(
"In Base: ",
this instanceof Base,
this instanceof Derived,
this.constructor.name
);
}
}
let thisInDerived;
class Derived extends Base {
constructor() {
super();
thisInDerived = this;
console.log(
"In Derived:",
this instanceof Base,
this instanceof Derived,
this.constructor.name
);
}
}
const instance = new Derived();
// =>
// In Base: true true Derived
// In Derived: true true Derived
console.log(instance === thisInBase);
// => true
console.log(instance === thisInDerived);
// => true