ECMAScript 5将严格模式引入javascript。使用严格模式的javascript静默错误很容易检测到,因为它们会引发错误。这使javascript调试更加容易,并有助于开发人员避免不必要的错误。
由于严格模式在遇到未声明的变量时会引发异常,因此将大大减少内存泄漏。严格模式可以通过在需要严格模式的代码前使用“ use strict”来启用。
在下面的示例中,使用了两个变量,一个在函数外部,另一个在函数内部。未声明在函数外部使用的变量,而在函数内部声明的变量使用var关键字声明。在函数内部使用严格模式不会引发任何错误,因为同时声明了变量,因为没有使用严格模式,所以将显示函数外部变量中的值。
<html>
<body>
<script>
myString1 = "non-strict mode will allow undeclared variables"
document.write(myString1);
document.write("</br>");
function myFun(){
"use strict"
var myString2 = "Strict mode will allow declared variables"
document.write(myString2);
}
myFun();
</script>
</body>
</html>non-strict mode will allow undeclared variables Strict mode will allow declared variables
在以下示例中,未在函数内部声明变量,而是应用了严格模式。因此,该变量内的值将不会执行并引发错误。我们可以在浏览器控制台中找到错误。
<html>
<body>
<script>
myString1 = "non-strict mode will allow undeclared variables"
document.write(myString1);
document.write("</br>");
function myFun(){
"use strict"
myString2 = "Strict mode will allow declared variables"
document.write(myString2);
}
myFun();
</script>
</body>
</html>non-strict mode will allow undeclared variables