在 JavaScript 中动态执行函数

发布于 2024-09-14 15:24:45 字数 274 浏览 3 评论 0原文

我想调用一个函数,其名称在变量中。

例如:
我动态获取字符串 "pageTracker._trackpageview('/url/page1.page'); " 并将其分配给如下变量

var myFunction = pageTracker._trackpageview('/url/page1.page');";

现在,当我提交页面时,我想执行以下函数在变量 myFunction 中。

谢谢大家。

I would like to call a function whose name I have in a variable.

For example:
I get the string "pageTracker._trackpageview('/url/page1.page'); " dynamically and assign it to a variable as below

var myFunction = pageTracker._trackpageview('/url/page1.page');";

Now when I submit the page I want to execute the function which is in variable myFunction.

Thank you all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

伊面 2024-09-21 15:24:45
function functionFromString(funcDef) {
   try {
      return (new Function("return function() {" + funcDef + "};"))();
   } catch (e) {
      alert(e);
      return (function() {});
   }
}

var myFunction = "pageTracker._trackpageview('/url/page1.page');";

var realFunction = functionFromString(myFunction);
realFunction();

为什么要这样做呢?

  1. 只需执行 eval 即可立即运行该函数。如果被调用函数本身抛出错误,我们无法区分它和解析错误之间的区别。因此,通过从文本中创建一个函数,我们可以将解析它的时间与执行它的时间分开。

  2. 仅使用 newFunction = Function(myFunction) 不会编译它,因此速度较慢。因此,使用 new Function() 返回一个函数(进而创建一个函数)是我们的技巧。我们也可以这样使用 eval,但我更喜欢 new Function。

其他人所说的关于对 eval (和 new Function())要非常小心的说法是正确的。它可能是恶意脚本的漏洞。

function functionFromString(funcDef) {
   try {
      return (new Function("return function() {" + funcDef + "};"))();
   } catch (e) {
      alert(e);
      return (function() {});
   }
}

var myFunction = "pageTracker._trackpageview('/url/page1.page');";

var realFunction = functionFromString(myFunction);
realFunction();

Why do it this way?

  1. Just doing eval runs the function right away. If there are errors thrown in the called function itself we can't tell the difference between that and an error in parsing. So by creating a function out of the text, we can separate when we parse it from when we execute it.

  2. Just using newFunction = Function(myFunction) won't compile it, so it's slower. So using new Function() to return a function (that in turn creates a function) is our trick. We could use eval this way, too, but I like new Function better.

What others have said about being really careful with eval (and new Function()) is true. It can be an opening for malicious script.

苏佲洛 2024-09-21 15:24:45

您可以使用 JavaScript eval() 函数来执行此操作。请小心控制传递给 eval() 的值,因为它将执行给定的任何字符串。

eval("pageTracker._trackpageview('/url/page1.page');");

You can do this with the JavaScript eval() function. Just be careful about controlling the value passed to eval() as it will execute whatever string it is given.

eval("pageTracker._trackpageview('/url/page1.page');");
﹏半生如梦愿梦如真 2024-09-21 15:24:45

您并不是简单地尝试执行一个其名称为的函数,而是执行一行带有接收器、方法名称和文字字符串参数的复杂代码。执行任意代码片段的唯一方法是使用 eval()eval() 是危险的。如果您不太小心,有人可能会将恶意代码传递到将在 eval() 调用内执行的脚本。

You are not simply trying to execute a function whose name you have but a complex line of code with a receiver, a method name and a literal string argument. The only way to execute an arbitrary snippet of codes is with eval() But eval() is dangerous. If you're not very careful, someone can pass malignant code to your script that will be executed inside the eval() call.

枕花眠 2024-09-21 15:24:45

您可以在 JavaScript 中使用 eval

var myFunction = "pageTracker._trackpageview('/url/page1.page');";
//...
eval(myFunction);

You can make use of eval in javascript..

var myFunction = "pageTracker._trackpageview('/url/page1.page');";
//...
eval(myFunction);
七婞 2024-09-21 15:24:45

解决方案:包装函数

//define:
var myFunction = function (){pageTracker._trackpageview('/url/page1.page');}

//call:
myFunction();

完整示例:

<html>
   <head>
      <script type="text/javascript">
         var foo = function (){alert('bar');}
      </script>
   </head>
   <body onload="foo();"> </body>
</html>

Solution: Wrap the function

//define:
var myFunction = function (){pageTracker._trackpageview('/url/page1.page');}

//call:
myFunction();

Full Example:

<html>
   <head>
      <script type="text/javascript">
         var foo = function (){alert('bar');}
      </script>
   </head>
   <body onload="foo();"> </body>
</html>
舟遥客 2024-09-21 15:24:45

但是这样,你就无法检查参数是否是正确的url,或者对其进行编码等。由于众所周知的原因,我极力避免评估。

我更喜欢更难,但更安全的方法 - 如果它是一个字符串,它可以被解析:

//test dub
pageTracker = {
   _trackpageview: function(path) {alert(path)}
}

var str = "pageTracker._trackpageview('/url/page1.page')";

//get param
var urlpathregex = /\('([a-z0-9\-._~%!
amp;'()*+,;=:@\/]+)'\)/;
var param = urlpathregex.exec(str)[1];

//do some stuff/validation with param
[...]

//get object and function name
var funcregex = /([a-zA-Z0-9_]+)?\.?([a-zA-Z0-9_]+)(?=\()/;
var match = funcregex.exec(str);
var obj, func;
obj = match[1];
func = match[2];

//invoke
window[obj][func](param);

这只是一个例子,而不是复制和粘贴准备好的代码:)因为首先 - 如果你动态获得“pageTracker._trackpageview ('/url/page1.page')" 作为字符串,这里已经有一些代码味道了。

But this way, you cannot check if parameter is correct url, or encode it ect. And I avoid eval as hell for known reasons.

I would prefer the harder, but more safe way - if it is a string, it can be parsed:

//test dub
pageTracker = {
   _trackpageview: function(path) {alert(path)}
}

var str = "pageTracker._trackpageview('/url/page1.page')";

//get param
var urlpathregex = /\('([a-z0-9\-._~%!
amp;'()*+,;=:@\/]+)'\)/;
var param = urlpathregex.exec(str)[1];

//do some stuff/validation with param
[...]

//get object and function name
var funcregex = /([a-zA-Z0-9_]+)?\.?([a-zA-Z0-9_]+)(?=\()/;
var match = funcregex.exec(str);
var obj, func;
obj = match[1];
func = match[2];

//invoke
window[obj][func](param);

This is just an example, and not copy&paste ready code :) Because to begin with - if you get dynamically "pageTracker._trackpageview('/url/page1.page')" as a string, there is some code smell here already.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文