严格模型和非严格模式的区别

严格模式 use strict,就是在代码的头部加上use strict 

function test(){
            console.log(arguments.callee)
            console.log(123)
        }
        test()
把这段代码放到浏览器是不会报错的,但是,如果严格模式是会报错的,小伙伴们可以拿过去代码去加上use strict在自己的浏览器上试试
因为严格模式是没有arguments,caller,callee
说一下这个callee 当函数本身 

function test(){
var i = 1
return function(){
i++;
console.log(11)
if(i<3){
arguments.callee()
}else{
return
}
}

}
test(1,2)()

他常用于递归调用。

function test1(){
            console.log(test1.caller)  //用他的函数
        }
        function demo(){
            test1()
        }
        demo()
 
caller是值得是调用它的函数。
谁调用的test1当然是demo了
 
 
不过如果你给他加上use strict他也会报错的,因为严格模式也不支持caller.
 
 
with(document){
            write('a')
        }
        var obj = {
            name:'ff'
        }
        var name = 'wind'
        function fn(){
            var name = 'scope'
            with(obj){
                console.log(name)
            }
        }
        fn()
with里面如果有对象,他就当作执行代码的最顶端,这里面我们fn()打印出来的就是ff,如果with里面没有东西的话,fn()打印的就是scope,
如果加上use strict直接就报错了
 
还有一条函数里面this不是window 在严格模式下
'use strict'
        function test(){
            console.log(this) //要想有值必须赋值 undefined
        }
        // new test()
        test()
        // test.call(123)
如果有new test()他里面就是生成的new 实例,
如果call的话这个this当然就是123
 
还有咱们关心的class类
 
class Person{
            constructor(name){
                this.name = name
            }
            get(){
                console.log(this)//默认严格模式
                // this.run()
            }
            run(){
                console.log(111)
            }
        }
        let person = new Person('zs')
        person.get()
        let {get} = person
        get()
        //es6类中默
class类里面this是undefined为什么?
因为get被暴露在了window下面,但是这个方法里面是严格模式我们自然知道打印的就是undefined
 
'use strict'
        function get(name,name){
            this.name = name
        }
        get(1)

        ///es5和标注浏览器的一个误差
        'use strict'
        var obj = {
            name:'d',
            name:'s'
        }
 
函数不能重名,对象这个检测不到浏览器
 
 
 
 
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/MDGE/p/12423835.html