将函数调用捕获为字符串

capturing function call as a string

本文关键字:字符串 函数调用      更新时间:2023-09-26

using JS;我正在传递一个函数名称作为可选参数。我想做一个开关案例来读取正在传递的函数名称。我将如何捕获函数变量,就好像它是一个字符串"函数变量"一样?

例:

function test(functionVariable)
{
  switch(functionVariable)
  {
    case firstFunction:
    alert('1st');
    break;
    case secondFunction:
    alert('2nd');
    break;
  }
}

当我提醒函数变量时,它会打印整个函数。这是有道理的,但我正在尝试解决它并获取函数名称。

编辑工作示例

function test(functionVariable)
{
  switch(functionVariable.name)
  {
    case firstFunction:
    alert('1st');
    break;
    case secondFunction:
    alert('2nd');
    break;
  }
}

你可以使用 Function.name。

function doSomething() {
  // does something
}
console.log(doSomething.name); // "doSomething"

请注意,这仅适用于函数声明和命名函数表达式。未命名的函数表达式将不起作用。

var getA = function getA() {
};
console.log(getA.name); // "getA"
var getB = function() { // Notice the lack of a name
};
console.log(getB.name); // ""
您可以使用

functionVariable.name,下面是一个例子:

x = function test() {}
console.log(x.name)
// logs "test"