2

This may seem a bit weird, but can come in handy when creating dynamic event listeners and I'll do my best to explain what I'm trying to achieve.

I have a variable and I want to create a function named after that variable value. Here's en example:

var functionName = "foo";
// Now I want to create a function named foo. foo is a tring

function [functionName](){
   alert('nothing really');
}

foo(); //Should alert "nothing really"

Thanks!

Bellash
  • 7,560
  • 6
  • 53
  • 86
Ood
  • 1,445
  • 4
  • 23
  • 43
  • By the way, I think you want quotes around "foo"; unless `foo` is a variable defined elsewhere, this is invalid syntax. – Ethan Brown Mar 11 '14 at 13:15

3 Answers3

12

Updated answer in 2016:

The "However, that's changing..." part of the original answer below has changed. ES2015 ("ES6") was released a year ago, and JavaScript engines are now finally coming into compliance with one of its lesser-known aspects: Function#name.

As of ES2015, this function has a name despite being created using an "anonymous" function expression:

var f = function() { };

Its name is f. This is dictated by the specification (or the new one for ES2016) in dozens of different places (search for where SetFunctionName is used). In this particular case, it's because it gets the name of the variable it's being assigned to. (I've used var there instead of the new let to avoid giving the impression that this is a feature of let. It isn't. But as this is ES2015, I'll use let from now on...)

Now, you may be thinking "That doesn't help me, because the f is hardcoded," but stick with me.

This function also has the name f:

let obj = {
    f: function() { }
};

It gets the name of the property it's being assigned to (f). And that's where another handy feature of ES2015 comes into effect: Computed property names in object initializers. Instead of giving the name f literally, we can use a computed property name:

let functionName = "f";
let obj = {
    [functionName]: function() { }
};

Computed property name syntax evaluates the expression in the [] and then uses the result as the property name. And since the function gets a true name from the property it's being assigned to, voilà, we can create a function with a runtime-determined name.

If we don't want the object for anything, we don't need to keep it:

let functionName = "f";
let f = ({
    [functionName]: function() { }
})[functionName];

That creates the object with the function on it, then grabs the function from the object and throws the object away.

Of course, if you want to use lexical this, it could be an arrow function instead:

let functionName = "f";
let f = ({
    [functionName]: () => { }
})[functionName];

Here's an example, which works on Chrome 51 and later but not on many others yet:

// Get the name
let functionName = prompt(
  "What name for the function?",
  "func" + Math.floor(Math.random() * 10000)
);

// Create the function
let f = ({
    [functionName]: function() { }
})[functionName];

// Check the name
if (f.name !== functionName) {
    console.log("This browser's JavaScript engine doesn't fully support ES2015 yet.");
} else {
    console.log("The function's name is: " + f.name);
}

Original answer from 2014:

What you've literally asked for is impossible without using eval unless you want the function to be global. If you do, you can do this:

// Creates global function
window[functionName] = function() { };

Note that that function won't actually have a name (in call stacks and such; but that's changing, see note below), but you can use the name in the variable to call it. So for example:

var functionName = "foo";
window[functionName] = function() {
    console.log("I got called");
};
foo(); // Outputs "I got called"

That's just a specific case of the more general purpose concept of using an object property. Here's a non-global function attached to an object property:

var functionName = "foo";
var obj = {};                       // The object
obj[functionName] = function() { }; // The function

obj[functionName] = function() {
    console.log("I got called");
};
obj.foo(); // Outputs "I got called"

In both cases, it works because in JavaScript, you can refer to a property either using dotted notation and a literal property name (obj.foo), or using bracketed notation and a string property name (obj["foo"]). In the latter case, of course, you can use any expression that evaluates to a string.


Just for completeness, here's how you'd do it with eval:

(function() { // This scoping function is just to emphasize we're not at global scope
  var functionName = "foo";
  eval("function " + functionName + "() { print('I got called'); }");
  foo();
})();

Here's the "note below" about function names: As of the current standard, ECMAScript 5th edition, this function has no name:

var f = function() { };

That's an anonymous function definition. Here's another one:

obj.f = function() { };

In the first, the variable has a name (f), but the function doesn't; in the second, the property on the object has a name, but the function doesn't.

However, that's changing. As of the 6th edition specification (currently still draft), the engine will give the function the name f, even with the expressions above. And it will infer names from slightly more complex expressions as well. Firefox's engine has already done at least some of it for a while, Chrome is starting to, and it'll be specified in the next edition of the spec.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Hm...T.J., I see the name of the function in the call stack no matter how I define it (I'm using Chrome). If I define it as a property of `window`, I see it as `window.foo` in the call stack. – Ethan Brown Mar 11 '14 at 13:23
  • 1
    @EthanBrown: That's because Chrome is implementing the upcoming changes per the ECMAScript6 draft specification. When faced with what used to be called an anonymous function expression, there are now various rules for inferring the function name. Firefox has done at least part of it for a while, and it's being spec'd. (Thanks for flagging it up, I added that to the answer.) – T.J. Crowder Mar 11 '14 at 13:58
  • Hey, any chance there is a way to do this with classes? `window[functionName] = function() { };` like `window[className] = class { };` except that doesn't work. – Barry Jul 01 '16 at 15:45
  • @Barry: Actually, with ES2015 it's possible without classes; I've updated the above to show how. – T.J. Crowder Jul 01 '16 at 16:22
  • I take it back. It actually does work to do `window[className] = class {}`, I was just making a mistake in my code. – Barry Jul 01 '16 at 16:24
  • @Barry: Yup, that works for the same reason it works with normal functions. – T.J. Crowder Jul 01 '16 at 16:27
3

"Global" functions in JavaScript are simply properties on the global context object (window in a browser). So you can do what you're looking for this way:

var functionName = 'foo';

window[functionName] = function() {
    alert('nothing really');
}
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
1

Node.js Object Based Dynamic Function Name with Execution

This syntax is somewhat similar to MongoDB / Mongoose Schema Virtuals. You provide the object with a method name and an execution context.

File: temp-obj.js

const modelInstance = {
  name: null,
  virtual(name = null) {
    if (!name) {
      throw new Error("Name is required");
    }
    this.name = name;
    // allows us to chain methods
    return this;
  },
  get(func = false) {
    if (!this.name || !func instanceof Function) {
      throw new Error("Name and function are required");
    }
    // Here we attach the dynamic function name to the "this" Object (which represents the current object modelInstance)
    this[this.name] = func;
    this.name = null;
  },
};
module.exports = modelInstance;

File: index.js

const modelInstance = require("./temp-obj.js");
// This is a two step approach, we name a function and provide it with an execution context
modelInstance.virtual("setMyCount").get((count) => {
  return { count: count };
});

const objVal = modelInstance.setMyCount(100);
console.log(objVal);

If interested, I have a similar response using a JavaScript Class Based Dynamic Function Name

Jason
  • 813
  • 11
  • 13