当我将其名称作为字符串时执行 JavaScript 函数 - 不工作

Execute a JavaScript function when I have its name as a string - Not working

我需要通过 var 字符串调用一个函数。我看到之前有人问过这个问题: How to execute a JavaScript function when I have its name as a string

但解决方案不起作用。我做错什么了吗? 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  
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');

您的代码按照编写的方式运行。正如许多人在评论中提到的那样,你的 JSFiddle 不起作用的原因是你假设 window 是你正在运行的全局范围。但是,您已将 JSFiddle JavaScript 设置为 运行 onLoad。这将它包装在 onload 处理程序中。因此,与您的假设相反,您的代码不是 运行 window 作为全局范围,这使得它不起作用。您可以通过将 JavaScript LOAD TYPE 选项更改为 No wrap - in <head>No wrap - in <body>.

让您的代码在 JSFiddle 上运行

这里是JSFiddle that has that change implemented.

此外,下面是您的代码片段,它运行良好。

// 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 
// 
//      /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');