ryan
ryan

Reputation: 45

capturing function call as a string

using JS; I am passing a function name as an optional argument. I would like to make a switch case that reads the functions name that is being passed. How would I capture the functionVariable as if it were a string "functionVariable"?

Example:

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

    case secondFunction:
    alert('2nd');
    break;
  }
}

When I alert functionVariable, it prints the whole function. It makes sense why but I'm trying to work around it and just get the functions name.

EDIT Working example

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

    case secondFunction:
    alert('2nd');
    break;
  }
}

Upvotes: 1

Views: 34

Answers (2)

Borys Serebrov
Borys Serebrov

Reputation: 16182

You can use functionVariable.name, here is an example:

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

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

You could use Function.name.

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

Note that this only works for function declarations and named function expressions. Unnamed function expressions won't work.

var getA = function getA() {
};
console.log(getA.name); // "getA"

var getB = function() { // Notice the lack of a name
};
console.log(getB.name); // ""

Upvotes: 1

Related Questions