Alphapage
Alphapage

Reputation: 919

Bind this to es6 class constructor

I'm trying to apply this to the constructor of an es6 class to get some kind of "constructor merging" like this:

class D {
    constructor(name){
        this.name=name
        this.methodD=function(){}
    }
}
class C extends D {
    constructor(name,name2){
        super(name)
        this.name2=name2
    }
}


function Custom(name,name2){
    if (this instanceof Custom){
         Function.prototype.bind.call(C.prototype.constructor,this,...arguments)
    }
}
Custom.prototype.method=function(){}
const cc=new Custom('name','name2')

I'm expecting cc to be constructed using the same constructor as C, so getting cc.name='name';cc.methodD();

Thank you in advance for your help.

Upvotes: 0

Views: 1390

Answers (1)

t1m0n
t1m0n

Reputation: 3431

You could try to create new instance of C inside of Custom and redefine prototype, using es6 Object.setPrototypeOf().

Please note that in this case Custom will only return object which will be constructed like C and its prototype will not contain methods of C.prototype and D.prototype, only their own methods, like methodD of D class.

Also note, that according to MDN article, this method could affect performance of browser.

class D {
    constructor(name){
        this.name=name
        this.methodD=function(){}
    }
}
class C extends D {
    constructor(name,name2){
        super(name)
        this.name2=name2
    }
}


function Custom(name,name2){
    let cls = new C(...arguments);
    Object.setPrototypeOf(cls, Custom.prototype);
    return cls;
}
Custom.prototype.method=function(){}
const cc=new Custom('name','name2')

console.log(cc.name)
console.log(cc.name2)
console.log(cc.methodD)
console.log(cc instanceof Custom)

Upvotes: 2

Related Questions