JavaScript 如何将字符串转换为函数

JavaScript 如何将字符串转换为函数

在本文中,我们将看到如何在JavaScript中将字符串转换为函数。有两种方法可以在JavaScript中将字符串转换为函数。第一种简单的方法是 eval() ,但它并不安全,因为它可以在没有权限的情况下在应用程序内运行,因此更容易受到第三方攻击。第二种方法是 Function() ,比eval()更安全。

  • Javascript eval(): 这个方法接受一个字符串作为参数,并将其转换为函数。这里的字符串可以是JavaScript表达式、变量、语句或语句序列。
  • Function构造函数: 使用Function构造函数创建的函数不会创建与它们所在上下文的闭包,它们总是在全局作用域中创建。它们只能在执行时访问自己的局部和全局变量,而不能访问Function构造函数所在作用域的变量。

示例1: 以下代码示例展示了使用Function构造函数将字符串转换为函数的另一种方法。

HTML

<!DOCTYPE html> 
<html> 
  
<body> 
    <h1 style="color:green"> 
        GeeksforGeeks 
    </h1> 
      
    <h3> 
        This example shows how we can transform string 
        into a function in javascript using Function 
        Constructor 
    </h3> 
  
    <p> The code output is : 
        <span id="result"></span> 
    </p> 
  
    <script> 
        var fnstring = "func"; 
        var fnparams = ["first", "second", "third"]; 
  
        // find an object 
        var fn = window[fnstring]; 
  
        // check if object a function? 
        if (typeof fn === "function") { 
            fn.apply(null, fnparams); 
        } 
  
        function func(a, b, c) { 
            document.getElementById("result").innerHTML = b; 
        } 
    </script> 
</body> 
  
</html> 

输出:

JavaScript 如何将字符串转换为函数

示例2: 下面的代码示例演示了将字符串转换为函数的不同方法。

HTML

<!DOCTYPE html> 
<html> 
  
<body> 
    <h1 style="color:green;"> 
        GeeksforGeeks 
    </h1> 
      
    <h3> 
        This example shows how we can transform string 
        into a function in javascript 
    </h3> 
    <h3>1. Use of eval()</h3> 
  
    <p> 
        When string "var func = function(){ return a+b }" is 
        passed in eval() and func() is called, The output is : 
        <span id="result"></span> 
    </p> 
  
    <h3>2. Use of Function constructor</h3> 
  
    <p> 
        When strings "x=5", "y=20", "return x*y" is 
        passed in Function constructor and fn() is called, 
        The output is : 
        <span id="func1"></span> 
    </p> 
  
    <p> 
        When strings "x=5", "y=20", "return x*y" is 
        passed in Function constructor and fn(4,10) is called, 
        The output is : 
        <span id="func2"></span> 
    </p> 
  
    <script> 
        // use of eval()     
        var a = 100; 
        var b = 200; 
        eval("var func = function(){ return a+b }"); 
        document.getElementById("result").innerHTML = func(); 
        // Use of Function Constructor 
        const fn = new Function("x=5", "y=20", "return x*y"); 
        document.getElementById("func1").innerHTML = fn(); 
        document.getElementById("func2").innerHTML = fn(4, 10); 
    </script> 
</body> 
  
</html> 

输出: 输出显示字符串转换为函数的过程。

JavaScript 如何将字符串转换为函数

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程