This is my first question on Stackoverflow so please dont run over me like a bulldozer if i did something wrong :)
I need to know if its possible in JavaScript classes to know, if the child has provided a constructor.
E.g.
class Parent {
constructor() {
console.log('Child has constructor:', /* Magic here */)
}
}
class Child extends Parent {}
new Child()
Expected output: Child has constructor: false
Vs:
class Parent {
constructor() {
console.log('Child has constructor:', /* Magic here */)
}
}
class Child extends Parent {
constructor() {
super()
}
}
new Child()
Expected output: Child has constructor: true
Background: I would like to have a class that behaves differently when it was extended than if it was used directly. Since Childs should provide the Parent different informations than if it was used directly.
No, it's not possible.
The class
syntax in JavaScript is just a syntax suger of a normal function
.
Take this ES6 example:
class Parent {
constructor(value){
this.example = value;
}
parentMethod(){
console.log('parent:', this.example);
}
}
class Child extends Parent {
childMethod(){
console.log('children:', this.example);
}
}
const parent = new Parent('Hello');
const child = new Child('World');
parent.parentMethod();
child.childMethod();
console.log(parent.constructor);
console.log(child.constructor);
As you can see, even if you don't explicitly define a constructor, a class will always have a constructor.
The above could roughly translate into the below ES5 code which does not yet support class
syntax:
function Parent(value){
this.example = value;
}
Object.defineProperties(Parent.prototype, {
parentMethod: {
writable: true,
enumerable: false,
configurable: true,
value: function(){
console.log('parent:', this.example);
}
}
});
function Child(value){
Parent.call(this, value);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype = Object.defineProperties(Child.prototype, {
childMethod: {
writable: true,
enumerable: false,
configurable: true,
value: function(){
console.log('child:', this.example);
}
}
});
var parent = new Parent('Hello');
var child = new Child('World');
parent.parentMethod();
child.childMethod();
console.log(parent.constructor);
console.log(child.constructor);
As you can see:
class
is merely just a function..constructor
is always assigned.Hence, there is no way for you to check if child class has a constructor because constructor is always there.
Even if you can do it (which you can't), the Parent will not know beforehand what class will extend it, so it will not know whether or not a future child will have a constructor or not.