原生js底层基础(十六)es5.0严格模式

mac2025-01-28  20

es5严格模式

不再兼容es3的一些不规则语法,使用全新的es5规范

1.用法(两种):

(1)全局严格模式

(2)局部严格模式(推荐)

2. es5.0严格模式启动

“use strict”

就是一行字符串,不会对不兼容严格模式的浏览器产生影响

(1)全局

写在页面逻辑最顶端:

"use strict" function test(){ //代码块 } test();
(2)局部

写在局部函数的最顶端:

function test(){ "use strict" //代码块 } test();

3. es5.0不支持部分

不支持with,arguments.callee,caller、变量赋值前必须声明、局部this必须被赋值、拒绝重复属性和参数

以下列举使用不支持部分的例子,在严格模式下会报错,可以分别尝试。

1)with()

es3.0支持,但es5.0禁用的一个函数 函数功能:此函数能通过参数改变直接作用域。例如,不同部门的人写同样的属性名,利用with方法不会变量污染

"use strict" var org = { dp1:{ a:{ name:"a" }, b:{ name:"b" } }, dp2:{ } } with(org.dp1.a){ console.log(name); //a } with(org.dp1.b){ console.log(name); //b } //报错 Uncaught SyntaxError: //Strict mode code may not include a with statement

2)arguments.callee()

函数功能:返回所在函数的引用

function test(){ "use strict" console.log(arguments.callee) } test(); //报错VM100:3 Uncaught TypeError: 'caller', 'callee', and 'arguments' //properties may not be accessed on strict mode functions or //the arguments objects for calls to them

3)不支持function.caller

函数功能:返回函数的调用环境

"use strict" function test(){ } function test(){ demo(); } function demo(){ console.log(demo.caller) } test(); //报错VM100:3 Uncaught TypeError: 'caller', 'callee', and 'arguments' //properties may not be accessed on strict mode functions or //the arguments objects for calls to them

4)变量赋值之前必须声明

function test(){ "use strict" id=123; console.log(id) } test() //Uncaught ReferenceError: name is not defined

5)局部this必须被赋值,可以赋值为任意,不赋值就默认为undefined

function test(){ "use strict" console.log(this) } test() undefined

6)拒绝重复属性和参数

function test(b,b){ "use strict" console.log(b+b) } test(1,3) //SyntaxError: Duplicate parameter name not allowed in this context

4.与es3冲突解决

当前浏览器基于es3.0+es5.0新增方法,即

对于es3.0和es5.0产生冲突的地方,开启es5.0严格模式的时候,他们冲突的部分就用es5.0,否则就用es3.0

最新回复(0)