严格模式与非严格模式区别

1、在严格模式中一部分字符变成了保留的关键字。这些字符包括implements, interface, let, package, private, protected, public, static和yield。在严格模式下,不能再用这些名字作为变量名或者形参名。

2、禁止使用with语句

3、创建eval作用域(严格模式下不能生成全局变量)

function f1() {
    eval('var a = 10')
    console.log(a)  //10
}

function f2() {
    'use strict'
    eval('var a = 10')
    console.log(a)  //ReferenceError: a is not defined
}

4、禁止全局函数中的this指向全局对象

function f1() {
    console.log(this)
}

function f2() {
    'use strict'
    console.log(this)
}
f1()    //window
f2()    //undefined

5、caller使用报错,arguments使用函数名调用报错,

function f1() {
    console.log(f1.caller)  //null
    console.log(f1.arguments)   //arguments类数组
}

function f2() {
    'use strict'
    console.log(arguments)      //arguments类数组
    console.log(f2.caller)      //TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them 
    console.log(f2.arguments)   //TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them 
}
f1()
f2()   

 arguments.callee使用报错

function f1() {
    console.log(arguments.callee)   //f1函数
}

function f2() {
    'use strict'
    console.log(arguments.callee)   //TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
}

arguments不再追踪参数变化,传进来多少就是多少

function f1(a) {
    a = 2
    console.log(arguments[0])   //2
}

function f2(a) {
    'use strict'
    a = 2
    console.log(arguments[0])   //1
}
f1(1)
f2(1)  

6、静默失败会报错

如delete不可配置的属性会报错

function f1() {
    var obj = {}
    Object.defineProperty(obj, 'a', {
        value: 1
    })
    delete obj.a
    console.log(obj.a)    //1
}

function f2() {
    'use strict'
    var obj = {}
    Object.defineProperty(obj, 'a', {
        value: 1
    })
    delete obj.a
    console.log(obj.a)  //TypeError: Cannot delete property 'a' of #<Object>
}

如对只读属性赋值会报错

function f1() {
    var obj = {}
    Object.defineProperty(obj, 'a', {
        value: 1
    })
    obj.a = 2
    console.log(obj.a)    //1
}

function f2() {
    'use strict'
    var obj = {}
    Object.defineProperty(obj, 'a', {
        value: 1
    })
    obj.a = 2
    console.log(obj.a)  //Cannot assign to read only property 'a' of object '#<Object>'
}

如对禁止扩展的对象添加新属性会报错

function f1() {
    var obj = {}
    Object.preventExtensions(obj)
    obj.a = 2
    console.log(obj.a)    //undefined
}

function f2() {
    'use strict'
    var obj = {}
    Object.preventExtensions(obj)
    obj.a = 2
    console.log(obj.a)  //Cannot add property a, object is not extensible
}

7、禁止0开头的8进制写法

function f1() {
    console.log(012)   //10
}

function f2() {
    'use strict'
    console.log(012)   //SyntaxError: Octal literals are not allowed in strict mode.
}
原文地址:https://www.cnblogs.com/lianglanlan/p/14427505.html