Variable Name Functions

Call a function using a variable. A variable with the value of a function name can call the function using this method.

Method 1 - standard functions

/*
fcn - function name
arg - argument(s) if any
*/
function run(fcn, arg) {
    return window[fcn](arg);
    // can also be: return top[fcn](arg);
    // can also be: return this[fcn](arg);
}

Example 1:

function callFunctionByVariable(msg) {
	return msg;
}
variableFunctionName = "callFunctionByVariable";
console.log(run(variableFunctionName, "hi"));
// console prints hi

 


 

 

Method 2 - prototype functions

 

// call: String.run();
String.prototype.run = function() {
    return window[this]();
}

Example 2:

Javascript (call these functions using variables)

For example purposes, there are a list of functions which return one word. Each function is called using variable values contained in an array corresponding to the function name. This demonstrates that a function call can be made from a variable.

Using the prototype function (Method 2), each of these functions will be called using variable values.

// list of functions to be called
function a() { return "This "; }
function b() { return "sentence "; }
function c() { return "is "; }
function d() { return "created "; }
function e() { return "by "; }
function f() { return "a "; }
function g() { return "list "; }
function h() { return "of "; }
function i() { return "function "; }
function j() { return "variable "; }
function k() { return "names"; }
function l() { return "."; }

// array of String values to be used to call the functions by the same name
functionList = ["a","b","c","d","e","f","g","h","i","j","k","l"];

// loop through the array and call the functions
// using the array String variable values
for (x=0; x<functionlist.length; x++) {
    document.getElementById("sentence").innerHTML += functionList[x].run();
}

HTML (put the result here)
<div id="sentence"></div>
Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use