You can do this by returning a proxy
from a
's constructor that intercepts name lookups and tests whether they are functions. If they are, call b
(unless you actually called b
):
class a {
constructor(){
const handler = {
get(target, propKey, receiver) {
const targetValue = Reflect.get(target, propKey, receiver);
if (typeof targetValue === 'function') {
return function (...args) {
// don't recursively call b
if (propKey !=='b') target.b()
return targetValue.apply(this, args); // call original function
}
} else {
return targetValue;
}
}
};
return new Proxy(this, handler);
}
b(){
console.log('b called')
}
c(arg){
console.log("c called with ", arg)
}
d(){
console.log("d called")
}
}
let instance = new a
instance.c("hello")
instance.d()
instance.b() // only called once
// still works for methods set after the fact:
a.prototype.g = function(){
console.log("g called")
}
instance.g() // still calls b