美文网首页
JavaScript严格模式

JavaScript严格模式

作者: 追逐_e6cf | 来源:发表于2019-02-17 16:44 被阅读0次

    严格模式

    在ES5引入,为了让团队开发更为便利、严谨,使用"use strict"开启严格模式。

    1. 变量必须声明之后再使用。
    "use strict";
    a = 1;
    console.log(a); //报错
    
    1. 函数的参数不能有同名的变量。
    "use strict";
    function add(a, a, b){}
    add();
    
    1. 不能使用with语句,with可以动态改变作用域,将要被废弃了。
    2. 不能对只读属性赋值。
    "use strict";
    var str = "123";
    str.length = 1;
    console.log(str.length);
    
    1. 不能删除不可删除的属性。
    "use strict";
    var str = "123";
    delete str.length;
    console.log(str.length);
    
    1. delete不能删除变量。
    "use strict";
    var str = "123";
    delete str;
    console.log(str);
    
    1. 不能使用前缀0表示八进制。
    "use strict";
    var num = 011; //报错
    //es6当中 8进制的前导值变为了0O 
    var num = 0O11; //8进制的76是十进制的多少? 7*8+6 = 62
    var num = 0x21; //16进制的21是十进制的多少?2*16+1 = 33
    var num = 0b1001; //1*2^0 + 0*2^1 + 0*2^2 + 1*2^3
    //进制转换
    console.log(num.toString(8));
    
    1. eval不会在他的外层作用域引入变量。
    2. eval和arguments不能被重新赋值
    "use strict";
    function add(){
        arguments = 3;
        console.log(arguments);
    }
    add(1,2,3);
    
    1. arguments不会自动反馈函数参数的变化
    2. 不能使用arguments.callee
    3. 不能使用arguments.callee.caller:表示函数的调用栈 (谁调用了这个函数,全局当中调用caller是null)
    "use strict";
    function add(){
        b();
    }
    function b(){
        console.log(arguments.callee.caller);
    }
    add(1,2,3);
    
    1. 禁止this指向全局对象
    "use strict";
    function add(){
        this.xx = 'lisi';
    }
    add();
    
    1. 不能使用fn.caller和fn.arguments获取函数的调用堆栈
    "use strict";
    function add(){
        b();
    }
    function b(){
        console.log(b.caller);
    }
    add(1,2,3);
    
    1. 增加了保留字 (比如protected,static和interface)。

    使用严格模式需要注意:

    1. 严禁在全局使用严格模式:ES5才开始有的,浏览器有的不支持,有些代码 也必须在非严格模式下使用。"use strict"也有作用域之分。
    function fn(){
        "use strict";
    }
    
    1. 如果希望在多个函数使用,但是不想多次声明"use strict";
    (function(){
        "use strict";
        function do(){
        }
        function do2(){
        }
    })()
    

    相关文章

      网友评论

          本文标题:JavaScript严格模式

          本文链接:https://www.haomeiwen.com/subject/vqigeqtx.html