调用变量中命名的JavaScript函数[duplicate]

时间:2022-06-25 20:24:57

This question already has an answer here:

这个问题已经有了答案:

I have a JavaScript variable which contains the name of a JavaScript function. This function exists on the page by having been loaded in and placed using $.ajax, etc.

我有一个JavaScript变量,它包含一个JavaScript函数的名称。该函数通过使用$加载并放置在页面上而存在。ajax,等等。

Can anyone tell me how I would call the javascript function named in the variable, please?

谁能告诉我如何调用变量中命名的javascript函数吗?

The name of the function is in a variable because the URL used to load the page fragment (which gets inserted into the current page) contains the name of the function to call.

函数的名称在变量中,因为用于加载页面片段(插入到当前页面)的URL包含要调用的函数的名称。

I am open to other suggestions on how to implement this solution.

对于如何实现这个解决方案,我有其他建议。

4 个解决方案

#1


224  

I'd avoid eval.

我避免eval。

To solve this problem, you should know these things about JavaScript.

要解决这个问题,您应该了解关于JavaScript的这些东西。

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. 函数是一级对象,所以它们可以是对象的属性(在这种情况下它们被称为方法),甚至是数组的元素。
  3. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  4. 如果您没有选择一个函数所属的对象,那么它属于全局范围。在浏览器中,这意味着您将它挂在名为“窗口”的对象上,这是全局变量所在的位置。
  5. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.
  6. 数组和对象是密切相关的。(传言他们甚至可能是乱伦的结果!)你可以用点代替。而不是方括号[],反之亦然。

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

您的问题是考虑了引用的点方式而不是方括号方式的结果。

So, why not something like,

为什么不呢,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

假设函数在全局空间中。如果你名称空间,那么:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

避免使用eval,避免将字符串传入setTimeout和setInterval。我写了很多JS,而且我从不需要eval。“需要”一词源于对语言了解不够深。您需要了解范围、上下文和语法。如果你一直在学习eval,那就去问一下——你很快就能学会。

#2


53  

If it´s in the global scope it´s better to use:

如果它´s在全球范围´s更好的使用:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

比eval()。因为evaaaaaal eval()。

Exactly like Nosredna said 40 seconds before me that is >.<

就像Nosredna在我之前40秒说的那是>。

#3


21  

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

一定要避免使用eval来做这样的事情,否则您将暴露自己的XSS(跨站点脚本)漏洞。

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

例如,如果您要使用这里提出的eval解决方案,一个邪恶的用户可以发送一个链接给他们的受害者,链接如下所示:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

http://yoursite.com/foo.html?func=function(){ alert(' Im % % 20 20格兰% 20 codez);}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

他们的javascript,而不是你的,会被执行。当然,这段代码所做的事情要比仅仅弹出一个警告要糟糕得多;它可以窃取cookie,向应用程序发送请求,等等。

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

因此,请确保从不对来自用户输入的不受信任的代码(以及查询字符串id中任何考虑用户输入的代码)进行eval。您可以将用户输入作为指向函数的键,但如果给定的字符串与对象中的键不匹配,则请确保不执行任何操作。例如:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

如果funcToRun变量没有指向myFuncs对象中的任何内容,但它不会执行任何代码,则此操作将失败。

#4


4  

This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:

这有点丑,但这是我第一次想到。这也应该允许您传递参数:

eval('var myfunc = ' + variable);  myfunc(args, ...);

If you don't need to pass in arguments this might be simpler.

如果您不需要传递参数,这可能会更简单。

eval(variable + '();');

Standard dry-code warning applies.

适用于标准dry-code警告。

#1


224  

I'd avoid eval.

我避免eval。

To solve this problem, you should know these things about JavaScript.

要解决这个问题,您应该了解关于JavaScript的这些东西。

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. 函数是一级对象,所以它们可以是对象的属性(在这种情况下它们被称为方法),甚至是数组的元素。
  3. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  4. 如果您没有选择一个函数所属的对象,那么它属于全局范围。在浏览器中,这意味着您将它挂在名为“窗口”的对象上,这是全局变量所在的位置。
  5. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.
  6. 数组和对象是密切相关的。(传言他们甚至可能是乱伦的结果!)你可以用点代替。而不是方括号[],反之亦然。

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

您的问题是考虑了引用的点方式而不是方括号方式的结果。

So, why not something like,

为什么不呢,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

假设函数在全局空间中。如果你名称空间,那么:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

避免使用eval,避免将字符串传入setTimeout和setInterval。我写了很多JS,而且我从不需要eval。“需要”一词源于对语言了解不够深。您需要了解范围、上下文和语法。如果你一直在学习eval,那就去问一下——你很快就能学会。

#2


53  

If it´s in the global scope it´s better to use:

如果它´s在全球范围´s更好的使用:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

比eval()。因为evaaaaaal eval()。

Exactly like Nosredna said 40 seconds before me that is >.<

就像Nosredna在我之前40秒说的那是>。

#3


21  

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

一定要避免使用eval来做这样的事情,否则您将暴露自己的XSS(跨站点脚本)漏洞。

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

例如,如果您要使用这里提出的eval解决方案,一个邪恶的用户可以发送一个链接给他们的受害者,链接如下所示:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

http://yoursite.com/foo.html?func=function(){ alert(' Im % % 20 20格兰% 20 codez);}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

他们的javascript,而不是你的,会被执行。当然,这段代码所做的事情要比仅仅弹出一个警告要糟糕得多;它可以窃取cookie,向应用程序发送请求,等等。

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

因此,请确保从不对来自用户输入的不受信任的代码(以及查询字符串id中任何考虑用户输入的代码)进行eval。您可以将用户输入作为指向函数的键,但如果给定的字符串与对象中的键不匹配,则请确保不执行任何操作。例如:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

如果funcToRun变量没有指向myFuncs对象中的任何内容,但它不会执行任何代码,则此操作将失败。

#4


4  

This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:

这有点丑,但这是我第一次想到。这也应该允许您传递参数:

eval('var myfunc = ' + variable);  myfunc(args, ...);

If you don't need to pass in arguments this might be simpler.

如果您不需要传递参数,这可能会更简单。

eval(variable + '();');

Standard dry-code warning applies.

适用于标准dry-code警告。