先程のperlエントリのjavascript版です
perlにおける関数/メソッドの動的呼び出し - end0tknrのkipple - web写経開発
javascriptでも関数/メソッドの動的呼び出しは可能ですが、
javascriptの場合、「new Function(...)」を利用する点が、perlと大きく異なります。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script> <script> function call_func(){ #### DYNAMIC CALL FUNCTION - no paramater var func_name = 'dynamic_call_func_1'; var func_obj = new Function("return "+func_name +"()"); func_obj(); #### DYNAMIC CALL FUNCTION - has paramater func_name = 'dynamic_call_func_2'; func_obj = new Function('arg_val', "return "+func_name +"(arg_val)"); func_obj('ABCDE'); #### DYNAMIC CALL METHOD var dynamic_obj = new DynamicCallClass(); func_name = 'dynamic_call_method_1'; func_obj = new Function('obj','arg_val',"return obj."+func_name +"(arg_val)"); func_obj(dynamic_obj,'ABCDE'); #### DYNAMIC CALL METHOD - (GoF - COMMAND PATTERN) var class_name = 'DynamicCallClass'; var func_obj = new Function("return new "+class_name+"()"); var cmd_obj = func_obj(); cmd_obj.dynamic_call_method_1('ABCDE'); } function dynamic_call_func_1(){ alert('12345'); } function dynamic_call_func_2(arg_val){ alert( arg_val ); } var DynamicCallClass = function() {}; DynamicCallClass.prototype = { dynamic_call_method_1: function(arg_val){ alert(arg_val); }, } </script> </head> <body> <button type="button" onClick="call_func()"> CALL FUNCTION </button> </body> </html>