Hammerbot
Hammerbot

Reputation: 16344

How can I create a class that "proxy" an object?

I want to create a class that behaves exactly like another class. But the object have to be already instantiated so I can't use heritage:

class Welcomer {
    sayHello () {
        console.log('Hello World')
    }
}

class Foo {
    private welcomer;

    constructor (welcomer: Welcomer) {
        this.welcomer = welcomer;
    }

    sayHello () {
        this.welcomer.sayHello();
    }
}

Basically, I want my Foo class to have every methods of the Welcomer class. And the methods on the Foo class should only call methods on the Welcomer class.

How can I do that without rewriting all the methods in the Foo class?

Upvotes: 1

Views: 140

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249686

You can use the Proxy class in ES2015 to intercept get/set calls and wrap the function and call the proxied implementation:

class Welcomer {
    sayHello() {
        console.log('Hello World')
    }
}

var welcomer = new Welcomer();
var proxy = new Proxy(welcomer, {
    get(target, prop) {

        var value = target[prop as keyof Welcomer];
        if(typeof value === 'function'){
            return function() {
                console.log(`Calling ${prop.toString()}`);
                value.apply(target, arguments);
            }
        }
        return value;
    }
})


proxy.sayHello()
proxy.foo() // error

Playground link

Upvotes: 2

Related Questions