简体   繁体   English

如何使用名称等于字符串的名称定义javascript函数

[英]How to define a javascript function with a name equal to a string

Let's say I'm given a string, and I want to define a function with a name of that string. 假设我给了一个字符串,并且我想用该字符串的名称定义一个函数。 How can I do this? 我怎样才能做到这一点?

UPDATE: 更新:

I forgot to mention that I do not want to set an anonymous function to a property because I would also like to dynamically grab the function's name from inside the function ie. 我忘了提到我不想为属性设置匿名函数,因为我也想从函数ie中动态获取函数的名称。 arguments.callee.name

Like this: 像这样:

var functionName = "myfunction"
window[functionName] = function() {
    // your function here
} 

Depending on the requirements, maybe something like this would work: 根据需求,也许这样的事情可能会起作用:

var myFunctionGenerator = function(name) {return function(message) {
    alert("hi, this is a function named '" + name + "'.  The parameter passed is '" + message + "'.");
}}

var myFunction = myFunctionGenerator('some function name');
myFunction('a parameter');
// hi, this is a function named 'some function name'.  The parameter passed is 'a parameter'.

If your declaring the function, use eval() . 如果您声明该函数,请使用eval() Just type a string representation of the argument your trying to execute for example: 只需键入您尝试执行的参数的字符串表示形式即可,例如:

eval("function name(){alert('a');}");

You can then call that method by normal convention, name(); 然后可以按照常规约定调用该方法name(); .

If you already have the function name and want to call that function with a string representation you can use the eval() method, although its not always optimal for performance. 如果您已经具有函数名称,并且想要使用字符串表示形式调用该函数,则可以使用eval()方法,尽管它并不总是针对性能而优化。 You will have this: 您将拥有:

var fnName = "functionName";
var params = "param1";
var fnNameWithParams = "functionName("+params+")";
eval(fnNameWithParams);

A better approach may be: 更好的方法可能是:

var fnName = "functionName";
var params = "param1";
var fnToCall = window[fnName];
fnToCall(params);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM