Babbel Bytes

Insights from the Babbel engineering team

JavaScript Function call interception

Tim

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 spies, stubs and mocks.

Facebook Twitter Google+ Reddit EMail
Comments