Extend external library methods with proxy
// mock external library class method
class Page {
goto = () => console.log('go to town');
setCookie = () => console.log('setting a cookie');
}
// extend external library classes with proxy
// proxy is a new global constructor function in es16
// new Proxy(target, handler);
class CustomPageProxy {
// use the static function to set up the proxy
static build() {
const page = new Page();
const customPageProxy = new CustomPageProxy(page);
const superPage = new Proxy(customPageProxy, {
get: function(target, property) {
return target[property] || page[property]; // check if method exists on extended class else use the method on parent class
}
});
return superPage;
}
constructor(page) {
this.page = page;
}
sendText = () => {
this.page.goto();
this.page.setCookie();
}
}
const superPage = CustomPageProxy.build();
superPage.sendText();
superPage.goto();