简体   繁体   English

如何运行存储在变量中的javascript函数?

[英]How do I run javascript functions stored in a variable?

I have a variable with instructions inside it, such as: 我有一个变量,里面有指令,例如:

runThis= "alert(); if(1>2) { alert("NO WAY");}";

How do I run the code inside runThis? 如何在runThis中运行代码?

eval(runThis);

But you shouldn't write code this way, it is difficult to manage. 但是您不应该以这种方式编写代码,这很难管理。

Do it like this instead : 这样做是这样的:

runThis= function () {
  alert(); 
  if(1>2) { 
    alert("NO WAY");
  };
}

then just call runThis 然后只需调用runThis

The dirty way to do this would be 这样做的肮脏方法是

eval(runThis);

This is, however, not reccommended at all. 但是,根本不建议这样做。

Alternatively, wrap it in a function 或者,将其包装在一个函数中

runThis = function(){ 
  // statements go here
}

And then you can call it runThis(); 然后可以将其runThis();

If you really want to do this kind of thing, you can use the eval() function: 如果您确实想做这种事情,可以使用eval()函数:

eval(runThis);

However this is not a recommended approach as it can lead to all kinds of difficult to diagnose bugs and errors 但这不是推荐的方法,因为它可能导致各种难以诊断的错误和错误

A better approach is to write a proper function with the code you wish to execute, and then assign it to a variable and invoke it via the variable: 更好的方法是使用您希望执行的代码编写适当的函数,然后将其分配给变量并通过该变量调用它:

//Assign function to variable
runThis = function(){ 
  alert();
  if(1>2) {
    alert("NO WAY");
  };
}

//Later, invoke the function
runThis();
code = "alert('test');";
eval(code);

WARNING: THIS IS A HORRIBLE PRACTICE! 警告:这是一种可怕的做法! DO NOT DO THIS! 不要这样做!

eval(runThis);

once you escaped your inner quotes properly. 一旦您正确地转义了内引号。

eval(runThis);

But it's not recommended. 但是不建议这样做。 Just remember eval() is evil . 只要记住eval() is evil

Eval will execute a string but you would be better off defining run this as follows. Eval将执行一个字符串,但最好定义运行如下。 And call it like any function. 并像调用任何函数一样调用它。

var runthis = function(){
     //code  here
}

But if you need to execute a string call eval. 但是,如果您需要执行字符串调用eval。

eval(runthis); eval(runthis);

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

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