Pick a language to speakRight Arrow
Ready to learn?
Pick a language to get started!

JavaScript Function call interception

Simple implementation in Javascript.
JavaScript Function call interception

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?
Author Headshot
Tim Koch-Grünberg
We are a team of more than 750 people from over 50 nations with a shared passion for languages. From our offices in Berlin and New York, we help people discover the joys of self-directed language learning. We currently offer 14 different languages — from Spanish to Indonesian — that millions of active subscribers choose to learn.
We are a team of more than 750 people from over 50 nations with a shared passion for languages. From our offices in Berlin and New York, we help people discover the joys of self-directed language learning. We currently offer 14 different languages — from Spanish to Indonesian — that millions of active subscribers choose to learn.

Recommended Articles

Students Are Now Eligible For Discounted Babbel Subscriptions

Students Are Now Eligible For Discounted Babbel Subscriptions

Brush up on your language studies with the app created by language teachers.
Quiz: Which Of The Best Foreign Films Should You Watch Next?

Quiz: Which Of The Best Foreign Films Should You Watch Next?

Some of the best movies out there are produced in another language. Find out which foreign film you should add to your must-see list!
Jargon Watch: Astronauts And The Language Of Space Travel

Jargon Watch: Astronauts And The Language Of Space Travel

What the heck is “puffy head bird legs”?