我正在尝试执行存储在变量中的函数并将参数传递给它。但是,在.apply
行上,我遇到了一个错误; Uncaught TypeError: Cannot call method 'apply' of undefined
小提琴:http://jsfiddle.net/valamas/vzesm/
function target(msg)
{
alert(msg);
}
function mainfunc (func)
{
var args = new Array();
for (var i = 1; i < arguments.length; i++)
args.push(arguments[i]);
console.log('args: ' + args);
//-- different attempts
window[func].apply(this, args);
//window[func].apply(null, Array.prototype.slice.call(arguments, 1));
//this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}
$(function ()
{
console.log('nnnnnnnnnnnnnnnnnn');
console.log('ready');
mainfunc('target', 'hello,', 'there!');
});
jsFiddle 并没有将 JS 放入全局范围,因此target
实际上不是 window
的属性。
添加此代码将使脚本正常工作:
window.target = target;
或者更明确地说:
window.target = function() { ...
演示:http://jsfiddle.net/Blender/vzesm/3/
这是因为在jsfiddle中javascript在不同的范围内执行。如果加载了 jQuery,您的代码将在 firebug 控制台中工作。对于 jsfiddle,您必须重写
如下target = function(msg)
{
alert(msg);
}
function mainfunc (func)
{
var args = new Array();
for (var i = 1; i < arguments.length; i++)
args.push(arguments[i]);
console.log('args: ' + args);
//-- different attempts
window[func].apply(this, args);
//window[func].apply(null, Array.prototype.slice.call(arguments, 1));
//this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}
$(function ()
{
console.log('nnnnnnnnnnnnnnnnnn');
console.log('ready');
mainfunc('target', 'hello,', 'there!');
});