如何使用"严格模式"保护我的 JavaScript?
在本教程中,我们将学习如何使用"严格模式"保护我的 JavaScript。代码中有一些错误会被 JavaScript 引擎忽略,如果任何一行失败,它不会执行任何操作,为了表明存在错误,我们可以使用严格模式,这将使 JavaScript 引擎抛出错误。
"use strict"是一个文字表达式,它是我们可以添加到代码中的指令,而不是任何块中。我们可以在整个脚本、函数或类中添加这个"use strict"指令。
语法
现在让我们来看看使用"严格模式"保护整个脚本的 JavaScript 的语法 -
<script> "use strict"; </script>
在上述语法中,我们在整个脚本中添加了"use strict"指令,如果整个代码中出现任何错误,它将使 JavaScript 引擎抛出错误。
现在让我们来看看使用"strict mode"保护特定函数的 JavaScript 的语法 −
<script> // normal code function name_of_function(){ "use strict"; // code for function } </script>
在上述语法中,我们在整个脚本中添加了"use strict"指令,如果整个代码中出现任何错误,它将使 JavaScript 引擎抛出错误。
我们已经了解了如何使用"严格模式"保护 JavaScript 的算法,现在让我们转到示例以了解实施的所有步骤。
示例 1
在此示例中,我们将对整个脚本使用严格模式,并在其中定义一些函数。我们将在脚本中初始化一个未声明的变量,以显示"use script"指令的使用。
<!DOCTYPE html> <html> <head> <script> "use strict"; a = 7; function function_one() { function nested() { document.getElementById("result").innerHTML = "This is the nested function of first function"; } nested(); document.getElementById("result").innerHTML += "<br> This is the first function"; } function function_second() { document.getElementById("result").innerHTML = "This is the second function"; } </script> </head> <body> <h3>How to secure my JavaScript using "Strict mode"?</h3> <p>Press this button to call the first function. <button onclick = "function_one()"> Press Me </button> </p> <p>Press this button to call the second function. <button onclick = "function_second()"> Press Me </button> </p> <p id = "result"> </p> </body> </html>
在上面的代码中,我们定义了代码主体,它定义了两个段落,每个段落都包含一个按钮。对于按钮,我们定义了 onclick 事件,该事件将在单击按钮时调用预定义函数。
在脚本中,我们在脚本开头添加了"use strict"指令,然后初始化了一个未声明的变量。之后,定义两个函数将在文档中写入,第一个函数还将包含一个嵌套函数。
示例 2
在此示例中,我们将使用严格模式(不是针对整个脚本),并将在脚本中定义一些函数。我们将创建两个函数,第一个函数将包含"use strict"指令和一个嵌套函数,第二个函数将只包含写入表达式。我们将在脚本中初始化一个未声明的变量,以显示"use script"指令的使用。
<!DOCTYPE html> <html> <head> <script> function function_one() { "use strict"; function nested() { document.write("This is the nested function of first function"); } nested(); document.write("<br> This is the first function"); } function function_second() { document.write("This is the second function"); } </script> </head> <body> <h3>How to secure my JavaScript using "Strict mode"?</h3> <p>Press this button to call the first function. <button onclick = "function_one()"> Press Me </button> </p> <p>Press this button to call the second function. <button onclick = "function_second()"> Press Me </button> </p> </body> </html>
在上面的代码中,我们定义了代码主体,它定义了两个段落,每个段落都包含一个按钮。对于按钮,我们定义了 onclick 事件,该事件将在单击按钮时调用预定义函数。
在脚本中,我们创建了两个函数,第一个函数将包含"use strict"指令和一个嵌套函数,第二个函数将仅包含书写表达式。
注意 − 在具有默认参数的函数中不允许使用严格模式。
例如
function add(first = 1, second = 2) { "use strict"; return first + second; }
上面的 JavaScript 代码将抛出语法错误,因为我们无法将"use strict"指令与默认参数函数一起使用。
结论
在本教程中,我们学习了如何使用"严格模式"保护我的 JavaScript。代码中有一些错误会被 JavaScript 引擎忽略,如果任何一行失败,它不会执行任何操作,为了表明存在错误,我们可以使用严格模式,这将使 JavaScript 引擎抛出错误。"use strict"是一个文字表达式,它是我们可以添加到代码中的指令,而不是任何块中。我们可以在整个脚本、函数或类中添加这个"use strict"指令。