JS学习笔记 之 ES5严格模式

ES标准 经历 es 1.0  es 3.0  es 5.0

当前,浏览器是 基于es 3.0 + es 5.0新增方法 实现

es 3.0 和 es 5.0 存在冲突

启用es 5.0的严格模式  -->  有冲突的部分就会使用es 5.0的方法

不启用es 5.0的严格模式  -->  有冲突的部分就会使用es 3.0的方法

es 5.0严格模式

'use strict'  //之所以用字符串进行标识,是因为如果使用类似于strict()函数的形式,某些没有实现ES5规范的浏览器找不到这样的函数,会有风险

(向后兼容,老的浏览器不会报错,新的浏览器能够识别出严格模式) 

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

  2. 两种用法

    - 全局严格模式

    - 局部函数内严格模式(推荐)

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

  4.      - 不支持with, callee, arguments, func, caller

        - 变量赋值前必须声明

        - 局部this必须被赋值(Person.call(null/undefined), 赋值什么就是什么)

        - 拒绝重复属性和参数(对象中有重复的属性名不会报错,但是后面的属性值会覆盖前面的)

启用es 5.0的严格模式:

1. 在顶端加上''use strict''

1  'use strict'; //es 5.0 严格模式的启动
2         function test(){
3             console.log(arguments.callee);
4         }
5         test();

执行上述代码后,报错如下:

类型错误,严格模式下,无法使用caller, callee, arguments等属性

 2. 在局部函数的顶端加上

1 function demo(){
2             console.log(arguments.callee);
3         }
4         demo();
5         function test(){
6             'use strict';
7             console.log(arguments.callee);
8         }
9         test();

执行结果如下:

demo()正常执行,test()报错

with函数:

改变内部函数的作用域链,可以简化代码,但是会影响系统运行效率

 1    var obj = {
 2        name : 'obj';
 3    }
 4        var name = 'window';
 5 
 6   function test(){
 7        var name = 'scope';
 8        with(obj){  //会把传入的参数放到with内函数作用域链的顶端
 9           console.log(name);           
10        }
11    }

test()执行后,打印 obj

利用with函数的特性,可以结合命名空间使用

 1  var org = {
 2             department1: {
 3                 alice : {
 4                     name : 'aaa',
 5                     age : 23
 6 
 7                 },
 8                 kirito : {
 9 
10                 }
11 
12             },
13             department2 = {
14 
15             }
16  }
17 
18  with(org.department1.alice){
19             //这里面的函数执行时,会优先到传入的参数空间中去查找变量
20  }

简化代码:一下的两个代码块都是实现在网页上打印字符a

1  with(document){
2             write('a');
3         }
document.write('a');

eval()函数

1    'use strict';
2    var a = 234;
3   eval('console.log(a)'); //作为参数的字符串会被当作正常的代码执行
原文地址:https://www.cnblogs.com/seveinn/p/11801502.html