How to execute a JavaScript function when I have i

2018-12-30 23:55发布

I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?

Depending on the circumstances, I may need to pass various arguments into the method too.

Some of the functions may take the form of namespace.namespace.function(args[...]).

标签: javascript
30条回答
裙下三千臣
2楼-- · 2018-12-31 00:15

Easiest way is to access it like has element

window.ClientSideValidations.forms.location_form

is same as

window.ClientSideValidations.forms['location_form']
查看更多
宁负流年不负卿
3楼-- · 2018-12-31 00:15

This is working for me:

var command = "Add";
var tempFunction = new Function("Arg1","Arg2", "window." + command + "(Arg1,Arg2)");
tempFunction(x,y);

I hope this works.

查看更多
忆尘夕之涩
4楼-- · 2018-12-31 00:16
use this

function executeFunctionByName(functionName, context /*, args */) {
      var args = [].slice.call(arguments).splice(2);
      var namespaces = functionName.split(".");
      var func = namespaces.pop();
      for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
      }
      return context[func].apply(context, args);
    }
查看更多
栀子花@的思念
5楼-- · 2018-12-31 00:20

Without using eval('function()') you could to create a new function using new Function(strName). The below code was tested using FF, Chrome, IE.

<html>
<body>
<button onclick="test()">Try it</button>
</body>
</html>
<script type="text/javascript">

  function test() {
    try {    
        var fnName = "myFunction()";
        var fn = new Function(fnName);
        fn();
      } catch (err) {
        console.log("error:"+err.message);
      }
  }

  function myFunction() {
    console.log('Executing myFunction()');
  }

</script>
查看更多
美炸的是我
6楼-- · 2018-12-31 00:21

With ES6 you could to access class methods by name:

class X {
  method1(){
    console.log("1");
  }
  method2(){
    this['method1']();
    console.log("2");
  }
}
let x  = new X();
x['method2']();

the output would be:

1
2
查看更多
栀子花@的思念
7楼-- · 2018-12-31 00:22

You can call javascript function within the eval("functionname as string") either. Like below: (eval is pure javascript function)

function testfunc(){
    return "hello world";
}

$( document ).ready(function() {

     $("div").html(eval("testfunc"));
});

Working example: https://jsfiddle.net/suatatan/24ms0fna/4/

查看更多
登录 后发表回答