Is there any easy way to inherit function constructor from class?
For example I have this code:
class Parent {
constructor() {
this.parentField = 1;
}
}
function Child() {
// Parent.call(this); // TypeError: class constructors must be invoked with 'new'
this.childField = 2;
}
Object.setPrototypeOf(Child, Parent);
Object.setPrototypeOf(Child.prototype, Parent.prototype);
const child = new Child();
console.log(child);
As you can see the problem is when I try to call constructor of class
The easiest way which I came up is to move code from constructor into class.prototype.initialize:
class Parent {
constructor() {
this.initialize();
}
initialize() {
this.parentField = 1;
}
}
function Child() {
Parent.prototype.initialize.call(this);
this.childField = 2;
}
Object.setPrototypeOf(Child, Parent);
Object.setPrototypeOf(Child.prototype, Parent.prototype);
const child = new Child();
console.log(child);
What if the class is written in some library or for some reason I don’t have access to this class?
The easiest way which I came up is to "recreate" the constructor of class:
class Parent {
constructor() {
this.parentField = 1;
}
}
function ParentConstructor(...args) {
const parent = new Parent(...args);
for (const key of Object.getOwnPropertyNames(parent)) {
this[key] = parent[key];
}
// or
// Object.setPrototypeOf(this, parent);
// but in this case I will not see the public keys of parent
}
function Child() {
ParentConstructor.call(this);
this.childField = 2;
}
Object.setPrototypeOf(Child, Parent);
Object.setPrototypeOf(Child.prototype, Parent.prototype);
const child = new Child();
console.log(child);
I want to know are there better ways to inherit function constructor from class for both situations:
- I have access to
class - I haven’t access to
class
>Solution :
Inheriting a class constructor in a function can be achieved by calling the class constructor within the function and manually setting the prototype chain.
class Parent {
constructor() {
this.parentField = 1;
}
}
function Child() {
let instance = Reflect.construct(Parent, arguments, new.target || Child);
instance.childField = 2;
return instance;
}
Object.setPrototypeOf(Child.prototype, Parent.prototype);
const child = new Child();
console.log(child);