Created
September 20, 2011 22:11
-
-
Save harrylove/1230566 to your computer and use it in GitHub Desktop.
A simple wrapper function in JavaScript - more fun with closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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)
??
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
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:)