javascript实现在函数中使用严格模式,使得未声明的变量不能被赋值
要在函数内部使用严格模式,可以在函数体的开始部分添加
'use strict';
语句。这样就可以使得函数内部的所有代码都运行在严格模式下。以下是一个示例函数:
function myFunction() {
'use strict';
myVar = 'Hello'; // this will cause an error because myVar is not declared
}
在这个函数中,如果'use strict';
语句没有被添加,myVar = 'Hello';
这行代码就会创建一个全局变量myVar
并将其赋值为'Hello'
,但是由于使用了严格模式,这行代码将会导致一个错误,因为myVar
变量没有被声明。
该博文为原创文章,未经博主同意不得转。本文章博客地址:https://cplusplus.blog.csdn.net/article/details/134172407