Skip to content
Advertisement

js redirect functions of one class to another

I have one class in JS (class1) which receives the class2 in the constructor.

Now, what I want to achieve is that I want to be able to call all the functions of class2 on the class1, but I don’t want to write all the function declarations in class1 and then each one of them calling on class2.

Is there any clean way of doing this ?

Advertisement

Answer

One option is to use a Proxy:

class Worker {
    constructor(name) {
        this.name = name
    }
    method1() {
        console.log(this.name, 'method1')
    }
    method2() {
        console.log(this.name, 'method2')
    }
}


class Facade {
    constructor(worker) {
        this.worker = worker
        return new Proxy({}, this)
    }
    get(target, prop) {
        return prop in this.worker ? this.worker[prop] : this[prop]
    }
    ownMethod() {
        console.log('facade own method')
    }
}

let f = new Facade(new Worker('worker1'))

f.method1()
f.method2()

f.ownMethod()

Another one is to copy method references to the facade object:

class Worker {
    constructor(name) {
        this.name = name
    }
    method1() {
        console.log(this.name, 'method1')
    }
    method2() {
        console.log(this.name, 'method2')
    }
}


class Facade {
    constructor(worker) {
        this.worker = worker
        for (let func of Object.getOwnPropertyNames(worker.constructor.prototype))
            this[func] = worker.constructor.prototype[func].bind(worker)
    }

    ownMethod() {
        console.log('facade own method')
    }
}

let f = new Facade(new Worker('me'))

f.method1()
f.method2()

f.ownMethod()

In Typescript you can use f = ... as (Facade & Worker) Playground Link, but there might be better solutions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement