I'm trying to figure out how I can reference an argument on a wrapper function stored in a variable that calls an anonymous function. Such as in the example below. The problem I run into is I'm used to accessing parameters via the arguments variable, but that sees only the parameter myFunc. I know it's supposed to be possible, but I can't figure out how.
var myFunc = function(arg1, arg2){//do stuff}
var myFuncWrapped = wrapper(myFunc);
myFuncWrapped('arg value1', 'arg value2');
function wrapper(func){
//how can I reference 'arg value1' from here since arguments == myFunc?
}
As the comment suggested, wrapper
should be returning a function so you can capture the arguments via closure when myFuncWrapped
gets called.
var myFunc = function(arg1, arg2) {
console.log(arg1); // (For testing only) Should be"arg value1"
};
var myFuncWrapped = wrapper(myFunc);
myFuncWrapped('arg value1', 'arg value2');
function wrapper(func) {
/* The anonymous function below is actually the one
* being called when you invoke "myFuncWrapped" so it has the arguments you need.
*/
return function() {
console.log(arguments[0]); // (For testing only) Should be"arg value1"
func.apply(this, arguments);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.