我试图通过传递函数名称并使用 apply() 在我的控件中执行外部 JS 函数。
我正在使用堆栈 here 上找到的解决方案
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
函数使用:
var functionName = 'MyFunction';
executeFunctionByName(functionName, window, [e, data]);
函数MyFunction:
function MyFunction(e, data){
// e <- this is an array [e, data]
// data <- this is undefined
}
根据documentation apply()
应按照函数定义中的形式传递参数,而不是作为数组。
有没有办法让它按照文档中描述的方式工作?
这与设置为窗口
的上下文有关吗?
最佳答案
之后
var args = Array.prototype.slice.call(arguments, 2);
尝试
console.log(args); // [[e, data]], array in array... got it?
所以有两种方法:
1)
executeFunctionByName(functionName, window, [e, data]);
至
executeFunctionByName(functionName, window, e, data);
2)
var args = Array.prototype.slice.call(arguments, 2);
至
var args = arguments[2]; //or name the third input parameter
关于JavaScript apply() 将所有参数作为一个数组传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27701947/