Skip to content

Instantly share code, notes, and snippets.

@harrylove
Created September 20, 2011 22:11
Show Gist options
  • Save harrylove/1230566 to your computer and use it in GitHub Desktop.
Save harrylove/1230566 to your computer and use it in GitHub Desktop.
A simple wrapper function in JavaScript - more fun with closures
var truth = function() { return true; };
var relativeTruth = function() { return false; };
var assert = function(func) {
return func() == true;
};
var wrapper = function(func) {
// perform setup work here
// executed once when wrapper() is executed
console.info('the wrap is set');
// The result of calling wrapper() is to return an anonymous
// function that has wrapped the original function in a closure
return function() {
// perform wrapped work here
// executed every time the wrapped function is called
console.info('wrap, wrap, wrap, the boys are marching');
// now call the original method
var args = Array.prototype.slice.call(arguments)[0];
return func(args);
}
};
assert = wrapper(assert); // the wrap is set
console.info(assert(truth)); // 'wrap wrap wrap the boys are marching', true
console.info(assert(relativeTruth)) // 'wrap wrap wrap the boys are marching', false
@Zibri
Copy link

Zibri commented Apr 9, 2019

oh and by the way this is a better wrapper:

var spy = function(func) {
  return function() {
        var args = [].splice.call(arguments, 0);
        console.log('function (', args, ')');
    return func.apply(this, args);
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment