使用Javascript:访问函数参数一般 [英] Javascript : accessing function arguments generically
本文介绍了使用Javascript:访问函数参数一般的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我:
var log = function(arg1, arg2){
console.log("inside :" + arg1 + " / " + arg2);
};
var wrap = function(fn){
return function(args){
console.log("before :");
fn(args);
console.log("after :");
}
};
var fn = new wrap(log);
fn(1,2);
这是错误的,因为我想在控制台中得到:
It is wrong, because I'd like to get in the console :
before :
inside :1 / 2
after :
但是我得到这个代替:
But I get this instead :
before :
inside :1 / undefined
after :
我如何知道的JavaScript ARGS
是传递给由返回的功能包装的所有参数
?
推荐答案
您可以使用<一个href=\"https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Objects/Function/apply\">apply调用与指定的本和参数数组的函数,所以尽量
You can use apply to call a function with a specified 'this' and argument array, so try
var wrap = function(fn){
return function(){
console.log("before :");
fn.apply(this, arguments);
console.log("after :");
}
};
这篇关于使用Javascript:访问函数参数一般的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文