[英]How to reference parent parameters of an anonymous function Javascript
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. 我遇到的问题是我习惯于通过arguments变量访问参数,但是只能看到参数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. 如注释所建议的, wrapper
应该返回一个函数,以便在调用myFuncWrapped
时可以通过闭包捕获参数。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.