JavaScript Function call interception

Simple implementation in Javascript.
Coding developer at coffee shop

Function call interception allows us to execute code before and after a function call. A use case might be formatting before and logging after a certain operation.


A simple implementation in JavaScript could look like this:

// http://jsbin.com/govubetamoli/5/watch?js,console

var myObj = {
  property: 1,
  sendTo: function (endpoint) {
    console.log('sending ' + this.property + ' to ' + endpoint);
  }
};

function format () {
  console.log('formatting ' + this.property);
}

function log () {
    console.log('logging ' + this.property);
}

before(myObj, 'sendTo', format);
after(myObj, 'sendTo', log);

myObj.sendTo('backend');

function before (object, method, fn) {
  var originalMethod = object[method];
  object[method] = function () {
    fn.apply(object);
    originalMethod.apply(object, arguments);
  };
}

function after (object, method, fn) {
  var originalMethod = object[method];
  object[method] = function () {
    originalMethod.apply(object, arguments);
    fn.call(object);
  };
}

This technique, also called function wrapping, is used by sinon.js to create spiesstubs and mocks.

Photo by Nicole Wolf on Unsplash

Want to join our Engineering team?
Apply today!
Share: