严格模式。

严格模式

为什么使用严格模式?

1.减少js代码的不规范使用和不合理运行。

2.提高运行速度。

类型

1.全局严格

2.局部严格

<script>
    "use strict"
  //  以下的所有代码都处于严格模式
 
</script>
<script>
    function obj(){
    
    
         "use strict"
       //该方法下的代码处于严格模式
   }
</script>

内容

1.不能使用未定义的变量。

<script>
	// 严格模式

  "use strict"
   x=123;       //报错( Uncaught ReferenceError: x is not defined)
</script>

2.不允许删除变量或者对象。

<script>

  "use strict";

   var x = 123;
   delete x;    // Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.
</script>

3.不允许变量重名。

<script>

  "use strict";
  function a(a1, a1) {
    
     // SyntaxError: Duplicate parameter name not allowed in this context
	   console.log(a1, a1)
   }   

</script>

4.不允许使用八进制。


<script>

  "use strict";
   var x = 010;   //Uncaught SyntaxError: Octal literals are not allowed in strict mode.

</script>

5.不允许修改只读属性的值。


<script>

  "use strict";
   var obj = {
    
    };
   Object.defineProperty(obj, "x", {
    
    
    value: 0,
    writable: false
   });
   obj.x = 3.14;     //Uncaught TypeError: Cannot assign to read only property 'x' of object '#<Object>'

</script>

6.不允许对只有getter方法的属性修改。


<script>
  "use strict";
   var obj = {
    
    
    get x() {
    
    
    return 0
    }
   };
   obj.x = 3.14;     //Uncaught TypeError: Cannot set property x of #<Object> which has only a getter

</script>

7.不允许删除对象的原型对象。


<script>

  "use strict";
   delete Object.prototype;   //Uncaught TypeError: Cannot delete property 'prototype' of function Object() { [native code] }(不能删除函数对象()的属性“原型”{ [本机代码] })

</script>

8.不能使用eval 或者arguments 作为变量名。

<script>
	//严格模式下
  "use strict";

   var eval = 3.14;    //Uncaught SyntaxError: Unexpected eval or arguments in strict mode(严格模式下的意外EVE或参数)
   console.log(eval)  

</script>
<script>
	// 严格模式下
  "use strict";

   var arguments = 3.14;    //Uncaught SyntaxError: Unexpected eval or arguments in strict mode(严格模式下的意外EVE或参数)
   console.log(arguments)  

</script>

9.严格模式下this指针的问题。

<script>
"use strict";
fun();
    function fun(){
    
    
        console.log(!this);//true
    }
    </script>

猜你喜欢

转载自blog.csdn.net/weixin_46953330/article/details/118977613
今日推荐