I need to call a function via a var string. I see that this question has been asked before: How to execute a JavaScript function when I have its name as a string
But the solution is not working. Did I do something wrong? https://jsfiddle.net/puLh9keg/
// a.callThis is the function that will be called using var string
var a = {
callThis:
function (ok, param1, param2) {
alert(ok + "|" + param1 + "|" + param2);
}
}
// Below is from https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string
function executeFunctionByName(functionName, context /*, args */) {
var args = [].slice.call(arguments).splice(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);
}
// try call a.callThis by var string
var fn = 'a.callThis';
executeFunctionByName(fn, window, true, 'param1', 'param2');