Bind this to es6 class constructor

Alphapage Source

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.

javascript

Answers

answered 6 months ago t1m0n #1

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)

comments powered by Disqus