Skip to content

Instantly share code, notes, and snippets.

@harrylove
Created September 20, 2011 22:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
@anhnt
Copy link

anhnt commented Nov 29, 2013

I'm confused with "arguments" varriable. Can you please explain a bit more detail. Thanks :)

@skyitachi
Copy link

maybe too late, i am a beginner of javascript;)
line 22 arguments means the args of the function which wrapper returns, just like line 27 assert = wrapper(assert)
the left hand assert;
forgive my poor english:)

@kimmobrunfeldt
Copy link

Shouldn't you call func like this?

return func.apply(this, args);

Currently it just calls func by passing arguments in a single Array.

See: https://gist.github.com/kimmobrunfeldt/ca53975d4ae9a7851fa9

@Zibri
Copy link

Zibri commented Apr 9, 2019

Let's say I do:

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

and then I do:
alert=spy(alert);
alert("hello");

this works, but how can I get the function name inside the closure?
so that it will do console.log(funcname,args)
??

@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