Skip to content

How to intercept method calls in JavaScript. Monkey patching vs. Proxies.

Notifications You must be signed in to change notification settings

MelkorNemesis/intercepting-method-calls

Repository files navigation

Intercepting method calls

Problem statement

Given this object

const myObj = {
  multiply(x, y) {
    return x * y;
  },
  squared(x) {
    return x ** x;
  }
};

and this method

function handleMethodCall(fnName, fnArgs) {
  console.log(`${fnName} called with `, fnArgs);
}

implement this function

function interceptMethodCalls(obj, fn) {
  // TODO
}

so that

interceptMethodCalls(myObj, handleMethodCall);
myObj.multiply(2, 7);
myObj.squared(2);

logs to the console

// multiply called with  [ 2, 7 ]
// squared called with  [ 2 ] 

Notes

If you need to, you can change more than just the interceptMethodCalls function. I've got two solutions and they slightly differ in how the interceptMethodCalls is invoked. But the parameters should stay the same.

Solutions

  1. Using Monkey Patching, Notes
  2. Using Proxy, Notes

About

How to intercept method calls in JavaScript. Monkey patching vs. Proxies.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published