我试图弄清楚如何引用存储在调用匿名函数的变量中的包装函数的参数。比如下面的例子。我遇到的问题是我习惯通过参数变量访问参数,但只能看到参数 myFunc。我知道这应该是可能的,但我不知道如何实现。
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?
}
最佳答案
正如评论所建议的,wrapper
应该返回一个函数,以便您可以通过 closure 捕获参数。当 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);
}
}
关于javascript - 如何引用匿名函数Javascript的父参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245713/