Javascript的严格模式

来源:互联网 发布:默纳克电脑调试软件 编辑:程序博客网 时间:2024/06/08 10:52

    Javascript除了正常的模式还有一种较为严格的模式:”严格模式“。设立严格模式主要是为了对Javascript的一些不合理进行完善,保证代码的安全性。

    进入严格模式需要声明严格模式,在脚本中输入'use strict',如果放在脚本第一行或者前面没有实际运行的语句,(比如aa)则整个脚本进入严格模式,如果有多个script标签,则有'use strict'语句的script标签进入严格模式,其他script标签下的Javascript仍然是正常模式。'use strict'可以放在函数中,是函数内部进入严格模式,函数外仍然是正常模式。

  <script>

   function aa(){
    "use strict";
      //执行语句按照严格模式
  }

  function bb() {
    //执行语句按照正常模式
  }

  </script>


    严格模式会对正常模式有所改变:

   (1)不允许使用with:

     //打印lh   18

     <script>

     var s={ 
           name:'lh',
           age:18
           }
    with(s){
    var str=name+"<br>";
    str+=age;
    document.write(str); 
     }

</script>

//  SyntaxError

<script>

"use strict";

     var s={ 
           name:'lh',
           age:18
           }
    with(s){
    var str=name+"<br>";
    str+=age;
    document.write(str); 
     }

</script>

(2)不允许为声明的变量被赋值 

//输出123

!function aa(){
   x=123;
   console.log(x);
  }();

//输出ReferenceError: x is not defined

!function aa(){
   "use strict";
   x=123;
   console.log(x);
  }();

(3)delete参数、函数名报错

    var s=11
    console.log(delete s);   //false


   "use strict";
   var s=11
   console.log(delete s);    //SyntaxError

(4)delete不可配置的属性报错

   console.log(delete Object.prototype);  //false

  "use strict";

  console.log(delete Object.prototype);  //TypeError

(5)禁止八进制字面量

console.log(0123);  //83

"use strict";

  console.log(0123);  //SyntaxError

(6)eval,arguments变为关键字,不能作为变量,函数名

  var arguments=10
  console.log(arguments);   //10

  var arguments=10
  console.log(arguments);  // SyntaxError

(7)eval 独立作用域

  eval( "var a=10");
  console.log(a);    //10

  "use strict";

   eval( "var a=10");
   console.log(a);    //ReferenceError: a is not defined

(8)arguments变为参数的静态副本

  //undefined
  (function(x){
   arguments[0]=50;
   console.log(x);
  }());
  //输出50
  (function(x){
   arguments[0]=50;
   console.log(x);
  }(10));
  //输出10
  (function(x){
   'use strict';
   arguments[0]=50;
   console.log(x);
  }(10))


  严格模式下函数调用时this指向null,而不是全局对象,当使用call/apply,传入null或undefined是时,this指向null或undefined而不是全局对象。在严格模式下,arguments.caller和arguments.callee被禁用。在ES5标准下,严格模式不允许对象重名,在ES6标准下,允许重名。ES6下对八进制有新的表示法(0o),在严格模式下能够正常转化为十进制。


原创粉丝点击