作为以下问题的后续,我需要将收到的参数发送给另一个函数。
例如:
myObj.RunCall("callName", 1,2,3,4,5);
myObj.RunCall("anotherCall", 1);
myObj.RunCall("lastCall");
在哪里
runCall = function(methodName)
{
// do something clever with methodName here, consider it 'used up'
console.log(methodName);
// using 'arguments' here will give me all the 'extra' args
var x = arguments.length;
// somehow extract all the extra args into local vars?
// assume there were 4 (there could be 0-100)
otherObj.DoIt(arg1, arg2, arg3, arg4); // here i need to send those "extra" args onwards
}
该.apply()
方法允许您使用数组中的参数调用函数。所以:
otherObj.DoIt(1,2,3);
// is equivalent to
otherObj.DoIt.apply(otherObj, [1,2,3]);
( to 的第一个参数.apply()
是将成为this
您正在调用的函数内的对象。)
因此,您只需要使用来自 的值创建一个数组arguments
,您可以使用它.slice()
来跳过第一个:
var runCall = function(methodName) {
console.log("In runCall() - methodName is " + methodName);
var extras = [].slice.call(arguments, 1);
otherObj.DoIt.apply(otherObj, extras);
}
// simple `otherObj.DoIt() for demo purposes:
var otherObj = { DoIt: function() { console.log("In DoIt()", arguments); }}
runCall("someMethod", 1,2,3);
runCall("someMethod", 'a', 'b');
runCall("someMethod");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句