0

This is some JS code

var methodArr = ['firstFunc','secondFunc','thirdFunc'];

for(var i in methodArr)
{

    window[methodName] = function()
    {
        console.log(methodName);
    }
}

My problem is that how to get the name of a function in JS.

In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?

Sorry, I didn't make it clear. I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
nice
  • 79
  • 1
  • 1
  • 7

1 Answers1

0

it seems a scope problem.

Try this:

var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
    var methodName = methodArr[i]; // <---- this line missed in your code?

    window[methodName] = (function(methodName) {
        return function() {
            console.log(methodName);
        }
    })(methodName);
}

window['secondFunc'](); // output: secondFunc
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52