Skip to content Skip to sidebar Skip to footer

Create A Javascript Function Dynamically From A String Name

Given a string classname, I want to dynamically create a new JavaScript function named after that string that can be used to instantiate objects. I've tried using eval() but for so

Solution 1:

Yes:

window[classname] = function() { ... };

Now, in honesty, that's not exactly like what you were attempting, but it's pretty close. When you instantiate a function via a functionexpression like that, and without a name, the function can't refer to itself except via the name in the outer scope (in this case, the global scope).

If that's important, what you could do is this: create the function with some stock "internal" name, and then assign it to the global name:

functionsecretName() { ... }

window[classname] = secretName;

Solution 2:

Try this:

var classname = "myFunction";

window[ classname ] = function () {};

alert( window[ classname ] ); // => undefined

Solution 3:

In case you don't want to create new functions based on some string, but based on another similar function: (this might not be a good example but hope you can get the idea)

functioncreateListOfFunctions(functionNameList) {
  resultFunctions = {};

  // Loop all names to create a list of functions with those names
  $.each(functionNameList, function(index, functionName) {
    resultFunctions[functionName] = _createFunction(functionName);
  });

  return resultFunctions;
}

function_createFunction(name) {
  returnfunction(anotherNameToCompare) {
    // customize this funciton whatever you likereturn name == anotherNameToCompare;
  };
}


// USAGE:
functionNameList = ['stack', 'overflow'];
result = createListOfFunctions(functionNameList); // result = { stack: function(name) {...}, overflow: function(name) {...} }

result.stack('stack'); // true
result.stack('not stack'); // false
result.overflow('overflow'); // true

Post a Comment for "Create A Javascript Function Dynamically From A String Name"