当我的名字作为字符串时,如何执行JavaScript函数

问题描述 投票:940回答:32

我在JavaScript中将函数的名称作为字符串。如何将其转换为函数指针,以便稍后调用?

根据具体情况,我可能还需要将各种参数传递给方法。

一些功能可能采取namespace.namespace.function(args[...])的形式。

javascript
32个回答
1354
投票

除非你绝对没有其他选择,否则不要使用eval

如前所述,使用这样的东西是最好的方法:

window["functionName"](arguments);

但是,这不适用于命名空间函数:

window["My.Namespace.functionName"](arguments); // fail

这是你怎么做的:

window["My"]["Namespace"]["functionName"](arguments); // succeeds

为了使这更容易并提供一些灵活性,这里有一个方便的功能:

function executeFunctionByName(functionName, context /*, args */) {
  var args = Array.prototype.slice.call(arguments, 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);
}

你会这样称呼它:

executeFunctionByName("My.Namespace.functionName", window, arguments);

注意,你可以传入你想要的任何上下文,所以这将与上面相同:

executeFunctionByName("Namespace.functionName", My, arguments);

10
投票

以下是我对Jason Bunting / Alex Nazarov的出色答案的贡献,其中包括Crashalot要求的错误检查。

鉴于此(人为的)序言:

a = function( args ) {
    console.log( 'global func passed:' );
    for( var i = 0; i < arguments.length; i++ ) {
        console.log( '-> ' + arguments[ i ] );
    }
};
ns = {};
ns.a = function( args ) {
    console.log( 'namespace func passed:' );
    for( var i = 0; i < arguments.length; i++ ) {
        console.log( '-> ' + arguments[ i ] ); 
    }
};
name = 'nsa';
n_s_a = [ 'Snowden' ];
noSuchAgency = function(){};

然后是以下功能:

function executeFunctionByName( functionName, context /*, args */ ) {
    var args, namespaces, func;

    if( typeof functionName === 'undefined' ) { throw 'function name not specified'; }

    if( typeof eval( functionName ) !== 'function' ) { throw functionName + ' is not a function'; }

    if( typeof context !== 'undefined' ) { 
        if( typeof context === 'object' && context instanceof Array === false ) { 
            if( typeof context[ functionName ] !== 'function' ) {
                throw context + '.' + functionName + ' is not a function';
            }
            args = Array.prototype.slice.call( arguments, 2 );

        } else {
            args = Array.prototype.slice.call( arguments, 1 );
            context = window;
        }

    } else {
        context = window;
    }

    namespaces = functionName.split( "." );
    func = namespaces.pop();

    for( var i = 0; i < namespaces.length; i++ ) {
        context = context[ namespaces[ i ] ];
    }

    return context[ func ].apply( context, args );
}

将允许您通过存储在字符串中的名称调用javascript函数,无论是命名空间还是全局,带或不带参数(包括Array对象),提供有关遇到的任何错误的反馈(希望能够捕获它们)。

示例输出显示了它的工作原理:

// calling a global function without parms
executeFunctionByName( '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 parms
executeFunctionByName( 'ns.a' );
  /* OUTPUT:
  namespace func passed:
  */

// calling a namespaced function passing a string literal
executeFunctionByName( '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 array 
executeFunctionByName( '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 literal
executeFunctionByName( 'n_s_a' );
  /* OUTPUT:
  Uncaught n_s_a is not a function
  */

// calling a non-existing function by string variable
executeFunctionByName( n_s_a );
  /* OUTPUT:
  Uncaught Snowden is not a function
  */

// calling an existing function with the wrong namespace reference
executeFunctionByName( 'a', {} );
  /* OUTPUT:
  Uncaught [object Object].a is not a function
  */

// calling no function
executeFunctionByName();
  /* OUTPUT:
  Uncaught function name not specified
  */

// calling by empty string
executeFunctionByName( '' );
  /* OUTPUT:
  Uncaught  is not a function
  */

// calling an existing global function with a namespace reference
executeFunctionByName( 'noSuchAgency', ns );
  /* OUTPUT:
  Uncaught [object Object].noSuchAgency is not a function
  */

9
投票

如果要使用window["functionName"]调用对象的函数而不是全局函数。你可以这样做;

var myObject=new Object();
myObject["functionName"](arguments);

例:

var now=new Date();
now["getFullYear"]()

8
投票

小心!!!

应该尽量避免在JavaScript中通过字符串调用函数,原因有两个:

原因1:某些代码混淆器会破坏您的代码,因为它们会更改函数名称,使字符串无效。

原因2:维​​护使用此方法的代码要困难得多,因为找到字符串调用的方法的用法要困难得多。


7
投票

根据您所在的位置,您还可以使用:

this["funcname"]();
self["funcname"]();
window["funcname"]();
top["funcname"]();
globalThis["funcname"]();

或者,在nodejs中

global["funcname"]()

6
投票

很惊讶没有提到setTimeout。

要运行不带参数的函数:

var functionWithoutArguments = function(){
    console.log("Executing functionWithoutArguments");
}
setTimeout("functionWithoutArguments()", 0);

要使用参数运行函数:

var functionWithArguments = function(arg1, arg2) {
    console.log("Executing functionWithArguments", arg1, arg2);
}
setTimeout("functionWithArguments(10, 20)");

要运行深度命名空间的函数:

var _very = {
    _deeply: {
        _defined: {
            _function: function(num1, num2) {
                console.log("Execution _very _deeply _defined _function : ", num1, num2);
            }
        }
    }
}
setTimeout("_very._deeply._defined._function(40,50)", 0);

6
投票

这是我的Es6方法,它允许您通过它的名称作为字符串或它的函数名称来调用您的函数,并且还允许您将不同数量的参数传递给不同类型的函数:

function fnCall(fn, ...args)
{
  let func = (typeof fn =="string")?window[fn]:fn;
  if (typeof func == "function") func(...args)
  else console.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

3
投票

所以,像其他人说的那样,绝对是最好的选择:

window['myfunction'](arguments)

Jason Bunting said一样,如果你的函数名包含一个对象,它将不起作用:

window['myobject.myfunction'](arguments); // won't work
window['myobject']['myfunction'](arguments); // will work

所以这是我的函数版本,它将按名称执行所有函数(包括对象与否):

my = {
    code : {
        is : {
            nice : function(a, b){ alert(a + "," + b); }
        }
    }
};

guy = function(){ alert('awesome'); }

function executeFunctionByName(str, args)
{
    var arr = str.split('.');
    var fn = window[ arr[0] ];
    
    for (var i = 1; i < arr.length; i++)
    { fn = fn[ arr[i] ]; }
    fn.apply(window, args);
}

executeFunctionByName('my.code.is.nice', ['arg1', 'arg2']);
executeFunctionByName('guy');

3
投票
  let t0 = () => { alert('red0') }
  var t1 = () =>{ alert('red1') }
  var t2 = () =>{ alert('red2') }
  var t3 = () =>{ alert('red3') }
  var t4 = () =>{ alert('red4') }
  var t5 = () =>{ alert('red5') }
  var t6 = () =>{ alert('red6') }

  function getSelection(type) {
    var evalSelection = {
      'title0': t0,
      'title1': t1,
      'title2': t2,
      'title3': t3,
      'title4': t4,
      'title5': t5,
      'title6': t6,
      'default': function() {
        return 'Default';
      }
    };
    return (evalSelection[type] || evalSelection['default'])();
  }
  getSelection('title1');

更多的OOP解决方案......


2
投票

关于杰森和亚历克斯的帖子的更多细节。我发现向上下文添加默认值很有帮助。只需将context = context == undefined? window:context;放在函数的开头即可。您可以将window更改为您喜欢的上下文,然后每次在默认上下文中调用它时都不需要传入相同的变量。


2
投票

我的代码中有一个非常类似的东西。我有一个服务器生成的字符串,其中包含一个函数名称,我需要将其作为第三方库的回调传递。所以我有一个代码,它接受字符串并返回函数的“指针”,如果找不到则返回null。

我的解决方案非常类似于“Jason Bunting's very helpful function*,虽然它不会自动执行,并且上下文总是在窗口上。但这很容易修改。

希望这对某人有帮助。

/**
 * 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, return
    if (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 parse
    return null;
}

98
投票

只是想我会发布一个略有改动的Jason Bunting's very helpful function版本。

首先,我通过向slice()提供第二个参数来简化第一个语句。原始版本在IE以外的所有浏览器中都运行良好。

其次,我在return语句中用上下文替换了它;否则,当执行目标函数时,这总是指向窗口。

function executeFunctionByName(functionName, context /*, args */) {
    var args = Array.prototype.slice.call(arguments, 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);
}

1
投票

还有一些非常有用的方法。

http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx

var arrayMaker = {  
    someProperty: 'some value here',  
    make: function (arg1, arg2) {  
        return [ this, arg1, arg2 ];  
    },
    execute: function_name
};

1
投票

要添加到Jason Bunting的答案,如果你正在使用nodejs或其他东西(这也适用于dom js),你可以使用this而不是window(并记住:eval是邪恶的:

this['fun'+'ctionName']();

1
投票

我无法抗拒提及另一个技巧,如果你有一个未知数量的参数也会有所帮助,这些参数也作为包含函数名称的字符串的一部分传递。例如:

var annoyingstring = 'call_my_func(123, true, "blah")';

如果您的Javascript在HTML页面上运行,您只需要一个不可见的链接;你可以将一个字符串传递给onclick属性,并调用click方法。

<a href="#" id="link_secret"><!-- invisible --></a>

$('#link_secret').attr('onclick', annoyingstring);
$('#link_secret').click();

或者在运行时创建<a>元素。


1
投票

最简单的方法是像有元素一样访问它

window.ClientSideValidations.forms.location_form

和...一样

window.ClientSideValidations.forms['location_form']

0
投票

不使用eval('function()')你可以使用new Function(strName)创建一个新函数。以下代码使用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>

0
投票
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);
    }

0
投票

看基本:

var namefunction = 'jspure'; // String

function jspure(msg1 = '', msg2 = '') { 
  console.log(msg1+(msg2!=''?'/'+msg2:''));
} // multiple argument

// Results ur test
window[namefunction]('hello','hello again'); // something...
eval[namefunction] = 'hello'; // use string or something, but its eval just one argument and not exist multiple

存在其他类型的功能是类和看起来示例nils petersohn


0
投票

谢谢你非常有帮助的答案。我在我的项目中使用Jason Bunting's function

我将它扩展为使用可选的超时,因为设置超时的正常方法不起作用。见abhishekisnot's question

function executeFunctionByName(functionName, context, timeout /*, args */ ) {
	var args = Array.prototype.slice.call(arguments, 3);
	var namespaces = functionName.split(".");
	var func = namespaces.pop();
	for (var i = 0; i < namespaces.length; i++) {
		context = context[namespaces[i]];
	}
	var timeoutID = setTimeout(
		function(){ context[func].apply(context, args)},
		timeout
	);
    return timeoutID;
}

var _very = {
    _deeply: {
        _defined: {
            _function: function(num1, num2) {
                console.log("Execution _very _deeply _defined _function : ", num1, num2);
            }
        }
    }
}

console.log('now wait')
executeFunctionByName("_very._deeply._defined._function", window, 2000, 40, 50 );

0
投票

这里有几个executeByName函数可以正常工作,除非name包含方括号 - 我遇到的问题 - 因为我有动态生成的名称。所以上面的函数会在名称上失败

app.widget['872LfCHc']['toggleFolders']

作为一种补救措施,我已经将功能考虑在内,也许有人会发现它很有用:

从CoffeeScript生成:

var executeByName = function(name, context) {
  var args, func, i, j, k, len, len1, n, normalizedName, ns;
  if (context == null) {
    context = window;
  }
  args = Array.prototype.slice.call(arguments, 2);
  normalizedName = name.replace(/[\]'"]/g, '').replace(/\[/g, '.');
  ns = normalizedName.split(".");
  func = context;
  for (i = j = 0, len = ns.length; j < len; i = ++j) {
    n = ns[i];
    func = func[n];
  }
  ns.pop();
  for (i = k = 0, len1 = ns.length; k < len1; i = ++k) {
    n = ns[i];
    context = context[n];
  }
  if (typeof func !== 'function') {
    throw new TypeError('Cannot execute function ' + name);
  }
  return func.apply(context, args);
}

为了更好的可读性,请检查CoffeeScript版本:

executeByName = (name, context = window) ->
    args = Array.prototype.slice.call(arguments, 2)
    normalizedName = name.replace(/[\]'"]/g, '').replace(/\[/g, '.')
    ns = normalizedName.split "."
    func = context
    for n, i in ns
        func = func[n]

    ns.pop()
    for n, i in ns
        context = context[n];
    if typeof func != 'function'
        throw new TypeError 'Cannot execute function ' + name
    func.apply(context, args)

0
投票

您也可以在eval("functionname as string")中调用javascript函数。如下所示:( eval是纯javascript函数)

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

$( document ).ready(function() {

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

工作示例:https://jsfiddle.net/suatatan/24ms0fna/4/


58
投票

这个问题的答案告诉你如何做到这一点:Javascript equivalent of Python's locals()?

基本上,你可以说

window["foo"](arg1, arg2);

或许多其他人建议,你可以使用eval:

eval(fname)(arg1, arg2);

虽然这是非常不安全的,除非你完全确定你正在评估什么。


0
投票

您所要做的就是使用上下文或定义您的函数所在的新上下文。你不仅限于window["f"]();

这是我如何对某些REST服务使用一些动态调用的示例。

/* 
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 class
    function 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.

如果你想从一个字符串生成整个函数,那就是一个不同的答案。另请注意,您不限于单个名称空间,如果您将名称空间存在为my.name.space.for.functions.etc.etc.etc,则您的名称空间的最后一个分支包含my.name.space.for.functions.etc.etc["function"]();函数

希望能帮助到你。 H。


50
投票

你能不能这样做:

var codeToExecute = "My.Namespace.functionName()";
var tmpFunc = new Function(codeToExecute);
tmpFunc();

您还可以使用此方法执行任何其他JavaScript。


42
投票

我认为这样做的一种优雅方式是在哈希对象中定义函数。然后,您可以使用字符串从哈希中引用这些函数。例如

var customObject = {
  customFunction: function(param){...}
};

然后你可以打电话:

customObject['customFunction'](param);

其中customFunction将是与对象中定义的函数匹配的字符串。


26
投票

使用ES6,您可以按名称访问类方法:

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

输出将是:

1
2

22
投票

两件事情:

  • 避免评估,它非常危险和缓慢
  • 其次,你的功能存在于哪里并不重要,“全球” - 无关紧要。 x.y.foo()可以通过x.y['foo']()x['y']['foo']()甚至window['x']['y']['foo']()启用。你可以像这样无限期地链接。

15
投票

所有答案都假设可以通过全局范围(aka窗口)访问这些函数。然而,OP没有做出这个假设。

如果函数存在于局部范围(也称为闭包)并且未被其他本地对象引用,那么运气不好:您必须使用eval()AFAIK,请参阅dynamically call local function in javascript


13
投票

你只需要通过window[<method name>]将你的字符串转换为指针。例:

var function_name = "string";
function_name = window[function_name];

现在你可以像指针一样使用它。

© www.soinside.com 2019 - 2024. All rights reserved.