I am trying to execute a function stored in a variable and pass params to it. However, on the .apply line, I am getting an error; Uncaught TypeError: Cannot call method 'apply' of undefined
Fiddle: 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('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n');
console.log('ready');
mainfunc('target', 'hello,', 'there!');
});
jsFiddle doesn’t put the JS into the global scope, so
targetisn’t actually a property ofwindow.Adding this code will make your script work:
Or to be more explicit:
Demo: http://jsfiddle.net/Blender/vzesm/3/