Quantcast
Channel: Babbel Bytes
Viewing all articles
Browse latest Browse all 115

JavaScript Function call interception

$
0
0

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.


Viewing all articles
Browse latest Browse all 115

Trending Articles