博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript 严格模式(use strict)
阅读量:4693 次
发布时间:2019-06-09

本文共 2243 字,大约阅读时间需要 7 分钟。

前言: 

"use strict" 指令在 JavaScript 1.8.5 (ECMAScript5) 中新增。

它不是一条语句,但是是一个字面量表达式,在 JavaScript 旧版本中会被忽略。

"use strict" 的目的是指定代码在严格条件下执行。

严格模式下你不能使用未声明的变量。

浏览器支持情况:

Internet Explorer 10 +、 Firefox 4+ Chrome 13+、 Safari 5.1+、 Opera 12+。

使用方式:

在脚本或函数的头部添加    "use strict";   表达式来声明。

针对全局要求使用严格模式:

"use strict";  fo() {   console.log('---')}

针对某个函数内部要求使用严格模式:

fo(){  "use strict";   console.log('---')}

主要作用:

  1. 消除版本javascript中一些不合理及不严谨之处,减少怪异行为
  2. 提高编译效率,提高运行速度
  3. 为新版本的javasript做铺垫兼容

语法说明:

1.不允许使用未声明的变量:

"use strict";x = 3.14; // 报错: Uncaught ReferenceError: x is not defined

2.不允许删除变量, 对象, 函数:

"use strict";var x = 3.14;delete x;               // 报错: Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

3.不允许函数的参数重名:

"use strict";function fo(x1, x1) {}; // 报错: Uncaught SyntaxError: Duplicate parameter name not allowed in this context

4.不允许使用八进制:

"use strict";var x = \010;           // 报错: Uncaught SyntaxError: Invalid or unexpected token

5.不允许对只读属性赋值::

"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 '#'

6.不允许对一个使用getter方法读取的属性进行赋值:

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

7.不允许删除一个不允许删除的属性:

"use strict";delete Object.prototype; // 报错: Uncaught TypeError: Cannot delete property 'prototype' of function Object() { [native code] }

8.变量名不能使用 "eval" 字符串:

"use strict";var eval = 3.14;         // 报错: Uncaught SyntaxError: Unexpected eval or arguments in strict mode

9.变量名不能使用 "arguments" 字符串:

"use strict";var arguments = 3.14;    // 报错: Uncaught SyntaxError: Unexpected eval or arguments in strict mode

 

10.禁止this关键字指向全局对象:

function f(){    return !this;} f() // 返回false,因为"this"指向全局对象,"!this"就是falsefunction f(){     "use strict";    return !this;} f() // 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。

因此,使用构造函数时,如果忘了加new,this不再指向全局对象,而是报错:

function f(){    "use strict";    this.a = 1;};f();// 报错,this未定义

  var a = function() {

    console.log(this)
  }
  a() // 输入window  
  var b =new a() //输出a对象

 

特别提示: "use strict" 指令只允许出现在脚本或函数的开头。

转载于:https://www.cnblogs.com/yalong/p/10286119.html

你可能感兴趣的文章
魔戒三曲,黑暗散去;人皇加冕,光明归来
查看>>
Error和Exception
查看>>
Python和Singleton (单件)模式[转载]
查看>>
httpclient设置proxy与proxyselector
查看>>
IT常用单词
查看>>
拓扑排序
查看>>
NYOJ--32--SEARCH--组合数
查看>>
JMS
查看>>
gulpfile 压缩模板
查看>>
【34.14%】【BZOJ 3110】 [Zjoi2013]K大数查询
查看>>
【 henuacm2016级暑期训练-动态规划专题 A 】Cards
查看>>
第五篇:白话tornado源码之褪去模板的外衣
查看>>
设备常用框架framework
查看>>
bootstrap模态框和select2合用时input无法获取焦点(转)
查看>>
21世纪经济网APP
查看>>
解决NetworkOnMainThreadException
查看>>
1039 到底买不买
查看>>
农银电商项目学习笔记(一)
查看>>
MockObject
查看>>
Chukwa
查看>>