Your code is invalid. ES6 is not TypeScript, so your class attributes must be declared inside your constructors. Moreover, you should follow a coding convention that favors pascal case over camel case for class names. Here is the correct syntax:
class BaseClass {
constructor(){
this.prop = 88;
console.log("BaseClass prop is", this.prop);
}
}
class DerivedClass extends BaseClass {
constructor(){
super();
this.prop = 83;
console.log("DerivedClass prop is", this.prop);
}
}
new DerivedClass();
So, why do we have 88 and 83? In fact, when your derived class calls the base class via super()
, this.prop
is 88 and you log it immediately. When super()
execution ends, this.prop
becomes 83, but there is no reason for your previous log to disappear...
Now, if you want private attributes for some reasons, you could declare them outside your constructors, but you would need IIFEs (Immediately-Invoked Function Expressions):
const BaseClass = (() => {
let prop = 88;
class BaseClass {
constructor(){
console.log("BaseClass prop is", prop);
}
}
return BaseClass;
})();
const DerivedClass = (() => {
let prop = 83;
class DerivedClass extends BaseClass {
constructor(){
super();
console.log("DerivedClass prop is", prop);
}
}
return DerivedClass;
})();
new DerivedClass();
As you can see, each class uses the prop
variable defined in its own scope.