zoukankan      html  css  js  c++  java
  • javascript strict mode

    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
    <script>
      "use strict";
      // global strict mode code here
    </script>
    // 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/

  • 相关阅读:
    Python-Celery分布式任务队列
    1、Go语言基础之变量和常量
    Django-使用支付宝支付
    jmeter处理http请求Content-Type类型和传参方式
    LR中解决接口请求中包含中文字符,服务器不识别的问题
    LoadRunner随机数
    LoadRunner参数传递给参数
    LoadRunner脚本编写
    [Scala] 语法基础
    [设计模式] 设计模式课程(十一)-- 单例模式
  • 原文地址:https://www.cnblogs.com/kidsitcn/p/8998211.html
Copyright © 2011-2022 走看看