/*** Converts a string containing a function or object method name to a function pointer.* @param string func* @return function*/function getFuncFromString(func) {// if already a function, returnif (typeof func === 'function') return func;
// if string, try to find function or method of object (of "obj.func" format)if (typeof func === 'string') {if (!func.length) return null;var target = window;var func = func.split('.');while (func.length) {var ns = func.shift();if (typeof target[ns] === 'undefined') return null;target = target[ns];}if (typeof target === 'function') return target;}
// return null if could not parsereturn null;}
var namefunction = 'jspure'; // String
function jspure(msg1 = '', msg2 = '') {console.log(msg1+(msg2!=''?'/'+msg2:''));} // multiple argument
// Results ur testwindow[namefunction]('hello','hello again'); // something...eval[namefunction] = 'hello'; // use string or something, but its eval just one argument and not exist multiple
// calling a global function without parmsexecuteFunctionByName( 'a' );/* OUTPUT:global func passed:*/
// calling a global function passing a number (with implicit window context)executeFunctionByName( 'a', 123 );/* OUTPUT:global func passed:-> 123*/
// calling a namespaced function without parmsexecuteFunctionByName( 'ns.a' );/* OUTPUT:namespace func passed:*/
// calling a namespaced function passing a string literalexecuteFunctionByName( 'ns.a', 'No Such Agency!' );/* OUTPUT:namespace func passed:-> No Such Agency!*/
// calling a namespaced function, with explicit context as separate arg, passing a string literal and arrayexecuteFunctionByName( 'a', ns, 'No Such Agency!', [ 007, 'is the man' ] );/* OUTPUT:namespace func passed:-> No Such Agency!-> 7,is the man*/
// calling a global function passing a string variable (with implicit window context)executeFunctionByName( 'a', name );/* OUTPUT:global func passed:-> nsa*/
// calling a non-existing function via string literalexecuteFunctionByName( 'n_s_a' );/* OUTPUT:Uncaught n_s_a is not a function*/
// calling a non-existing function by string variableexecuteFunctionByName( n_s_a );/* OUTPUT:Uncaught Snowden is not a function*/
// calling an existing function with the wrong namespace referenceexecuteFunctionByName( 'a', {} );/* OUTPUT:Uncaught [object Object].a is not a function*/
// calling no functionexecuteFunctionByName();/* OUTPUT:Uncaught function name not specified*/
// calling by empty stringexecuteFunctionByName( '' );/* OUTPUT:Uncaught is not a function*/
// calling an existing global function with a namespace referenceexecuteFunctionByName( 'noSuchAgency', ns );/* OUTPUT:Uncaught [object Object].noSuchAgency is not a function*/
/*Author: Hugo Reyes@ www.teamsrunner.com
*/
(function ( W, D) { // enclose it as self invoking function to avoid name collisions.
// to call function1 as string// initialize your FunctionHUB as your namespace - context// you can use W["functionX"](), if you want to call a function at the window scope.var container = new FunctionHUB();
// call a function1 by name with one parameter.
container["function1"](' Hugo ');
// call a function2 by name.container["function2"](' Hugo Leon');
// OO style classfunction FunctionHUB() {
this.function1 = function (name) {
console.log('Hi ' + name + ' inside function 1')}
this.function2 = function (name) {
console.log('Hi' + name + ' inside function 2 ')}}
})(window, document); // in case you need window context inside your namespace.
function convertStringtoFunction(functionName){
var nullFunc = function(){}; // Fallback Null-Functionvar ret = window; // Top level namespace
// If null/undefined string, then return a Null-Functionif(functionName==null) return nullFunc;
// Convert string to function namefunctionName.split('.').forEach(function(key){ ret = ret[key]; });
// If function name is not available, then return a Null-Function else the actual functionreturn (ret==null ? nullFunc : ret);
}
function fnCall(fn, ...args){let func = (typeof fn =="string")?window[fn]:fn;if (typeof func == "function") func(...args);else throw new Error(`${fn} is Not a function!`);}
function example1(arg1){console.log(arg1)}function example2(arg1, arg2){console.log(arg1 + " and " + arg2)}function example3(){console.log("No arguments!")}
fnCall("example1", "test_1");fnCall("example2", "test_2", "test3");fnCall(example3);fnCall("example4"); // should raise an error in console
function runDynamicFn(fnName, ...args) {// can also be fed from a tightly controlled configconst allowedFnNames = ['fn1', 'ns1.ns2.fn3', 'ns4.fn4'];
return allowedFnNames.includes(fnName) ? eval(fnName)(...args) : undefined;}
// test function:function fn1(a) {console.log('fn1 called with', a)}
runDynamicFn('alert("got you!")')runDynamicFn('fn1', 'foo')
function fun1(arg) {console.log(arg);}
function fun2(arg) {console.log(arg);}
const operations = {fun1,fun2};
operations["fun1"]("Hello World");operations.fun2("Hello World");
// You can use intermediate variables, if you likelet temp = "fun1";operations[temp]("Hello World");
它还可以使用导入的函数:
// mode.jsexport function fun1(arg) {console.log(arg);}
export function fun2(arg) {console.log(arg);}
let executor = new FunctionExecutor();executor.addFunction(two)executor.addFunction(three)
executor.execute("one");executor.execute("three");
显然,在项目中,需要按名称调用的所有函数的添加都是由循环完成的。
执行器的功能:
function FunctionExecutor() {this.functions = {};
this.addFunction = function (fn) {let fnName = fn.name;this.functions[fnName] = fn;}
this.execute = function execute(fnName, ...args) {if (fnName in this.functions && typeof this.functions[fnName] === "function") {return this.functions[fnName](...args);}else {console.log("could not find " + fnName + " function");}}
this.logFunctions = function () {console.log(this.functions);}}
示例用法:
function two() {console.log("two");}
function three() {console.log("three");}
let executor = new FunctionExecutor();executor.addFunction(two)executor.addFunction(three)
executor.execute("one");executor.execute("three");
function captchaTest(msg){let x = Math.floor(Math.random()*(21-1)) +1;let y = Math.floor(Math.random()*(11-1)) +1;let sum = function(){return x+y;}let sub = function(){if (y > x){let m = y;y = x;x = m;console.log(x,y,m,'--')}return x-y;}let mul = function(){return x*y;}let OParr = [sum(), sub(), mul()];let OP = Math.floor(Math.random()*OParr.length);let s = OParr[OP]; //!!! HERE !!! is the call as array elementswitch(OP){case 0:opra = '+';break;case 1:opra = '━';break;default:opra = '✖';}let msg2 = 'Answer the following question to continue:'let p = prompt(msg+' '+msg2+'\n'+'What is the result of '+x+opra+y+' ?','')console.log(s,p,OP)if (s == p){alert ('Wow, Correct Answer!')return true;}else{alert('Sorry, the answer is not correct!')return false;}}