博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript strict mode
阅读量:7038 次
发布时间:2019-06-28

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

ECMAScript 版本5是目前最广泛使用的js版本。

其中的一个重要feature strict mode很多人不是很清除和理解。

什么是strict mode?

strict mdoe是一种强制js解释引擎以一种和非stric mode不同的语义的方式来解释javascript代码。运行于script mode的代码有以下几个特征:

1. 剔除一些句法和语义功能,也就是说,你不能象传统js那样随心所欲

2. 修正部分功能的语义,即:一部分代码在strict mode和非strict mode下执行的语义是不同的。

3. 如果有语法或者语义的歧义,在stric mode下直接报出错误,而非隐含运行;

4. stric mode仅仅应用于代码段,也就是说,你不能将strict mode一次性应用到所有js文件中,除非你concat所有的js文件.

stric mode出现的主要白目的是在js开发过程中,强制一些运行时的discipline. 我总是感觉js实在太过灵活,而stric mode就是将这个灵活做以下限制。很多时候之前必须由资深工程师自己注意的tricky部分,那么现在就由stric mode强加进来了。比如看看下面这段代码,你看有什么问题吗?实际上"stric mode"下,js引擎就会报错:

function findProduct(numbers) {    "use strict";    var product = 0,        len = numbers.length;    for(var i = 0; i < len; ++i) {        prodct = product * numbers[i]; // ReferenceError: Variable undefined in strict mode    }    return product;}

 

浏览器支持情况:

几乎所有的现代浏览器都在他们的js引擎中支持strict mode. IE10以上都支持strict mode,

strict mode contexts:

"use strict";alert("Look ma! Strict mode!");

几种使能方式:

// global code// 2. Eval code:eval("'use strict'; // strict code here");// or invoked from strict mode code:"use strict";eval("// strict code here");// function code:function foo() {    "use strict";    // strict code here}// Functions declared in strict mode code inherit the strictness:function foo() {    "use strict";    var bar = function () {        // strict code here    };    bar();}

 strict mode到底有哪些新的限制呢?

1. 标示符必须在他们被赋值前声明:

2. 对于没有context的function call不会自动赋予context,比如如果函数被调用不给一个obj.method这种方式的话,函数并不会给于this为window对象。

function foo() {    // prints "true"    print(this === window);}foo();function foo() {    "use strict";    // prints "false"    print(this === window);}foo();

3. reserved keywords不能用于标示变量名

"use strict";var yield; // SyntaxError: Expected identifier

 

https://blogorama.nerdworks.in/javascriptstrictmoderestrictio/

转载于:https://www.cnblogs.com/kidsitcn/p/8998211.html

你可能感兴趣的文章
《Spark大数据分析:核心概念、技术及实践》一2.3 一个单独的Scala应用程序
查看>>
Phalcon入门教程之模型
查看>>
K近邻算法-KNN
查看>>
北京这两天为啥颜值爆表?
查看>>
HybridDB · 最佳实践 · HybridDB 数据合并的方法与原理
查看>>
《Unity着色器和屏幕特效开发秘笈(原书第2版)》一2.2 漫反射着色
查看>>
利用Fork/Join框架来统计某个字符串在某个文件夹的文件中出现的次数
查看>>
使用ownCloud在Linux安装你的个人云服务
查看>>
《深入实践Spring Boot》一1.6 小结
查看>>
XTTS,又一个值得你重视的Oracle数据库迁移升级利器
查看>>
error: src refspec master does not match any. error: failed to push some refs to
查看>>
《C语言及程序设计》实践项目——用break和continue改变流程
查看>>
Nodejs进阶:基于express+multer的文件上传
查看>>
利用ROS搭建应用基础套件
查看>>
MySQL · 物理备份 · Percona XtraBackup 备份原理
查看>>
The total number of locks exceeds the lock table size错误(已纠正)
查看>>
Java千百问_05面向对象(005)_接口和抽象类有什么区别
查看>>
c++虚函数表探究
查看>>
java自定义注解
查看>>
Zend的Registry机制
查看>>