JavaScript 如何从字符串中的名称调用函数

JavaScript 如何从字符串中的名称调用函数

在本文章中,我们将从存储在变量中的字符串调用函数。有两种方法可以从存储在变量中的字符串调用函数。

  • 使用window对象方法
  • 使用eval()方法

注意:eval()方法已经过时,不推荐使用。

方法1:使用window对象

HTML 5中的window对象引用当前窗口及其中包含的所有项。因此,我们可以使用它来运行一个包含参数的字符串函数。

语法:

window[functionName](parameters)

示例: 此示例解释了上述使用的方法。

<h1 style="color: green"> 
    GeeksforGeeks 
</h1> 
  
<b> 
    How to call function from string stored 
    in a variable using JavaScript 
</b> 
  
<p> 
    Click on the button to call the 
    function in the string 
</p> 
  
<p class="example"> 
    GeeksforGeeks is a computer 
    science portal. 
</p> 
  
<button onclick="evaluateFunction()"> 
    Click here 
</button> 
  
<script type="text/javascript"> 
    function changeColor(color) { 
        document.querySelector('.example').style 
            = `color: ${color}`; 
    } 
      
    function evaluateFunction() { 
        stringFunction = "changeColor"; 
        param = 'green'; 
        window[stringFunction](param); 
    } 
</script>

输出:

JavaScript 如何从字符串中的名称调用函数

方法2:使用eval()方法

另一种方法是使用eval()方法。传递给函数的字符串可能包含JavaScript表达式、语句或一系列语句。它还可以具有现有对象的变量和属性。这种方法的唯一问题是它被认为是不安全的,可能不被新版本的浏览器支持。

语法:

eval(stringFunction)

示例: 此示例解释了上述使用的方法。

<h1 style="color: green"> 
    GeeksforGeeks 
</h1> 
  
<b> 
    How to call function from string stored 
    in a variable using JavaScript 
</b> 
  
<p> 
    Click on the button to call the 
    function in the string 
</p> 
  
<p class="example"> 
    GeeksforGeeks is a computer 
    science portal. 
</p> 
  
<button onclick="evaluateFunction()"> 
    Click here 
</button> 
  
<script type="text/javascript"> 
    function changeColor(color) { 
        document.querySelector('.example').style 
                = `color: ${color}`; 
    } 
          
    function evaluateFunction() { 
        stringFunction = "changeColor('green')"; 
        eval(stringFunction); 
    } 
</script>

输出:

JavaScript 如何从字符串中的名称调用函数

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程