美文网首页
严格模式 学习笔记

严格模式 学习笔记

作者: squidbrother | 来源:发表于2021-07-01 20:41 被阅读0次
    1. 什么是严格模式
      严格模式是ECMAScript5中新增的,用于严苛规范javascript脚本执行的模式

    2. 严格模式的意义何在
      消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;
      具体:

    • 消除代码运行的一些不安全之处,保证代码运行的安全;
    "use strict";
    eval ("var x = 2"); // eval() 创建的变量不能被调用:
    alert (x);     
    
    • 提高编译器效率,增加运行速度;

    • 为未来新版本的Javascript做好铺垫;
      变量先声明后使用的缺陷设计

    "use strict";
    x = 3.14;                // 报错 (x 未定义) 
    
    1. 严格模式怎么用,需要注意什么
    • 开启方式:
      javascript文件内 在顶部添加 use strict; 表达式来开启严格模式
    <script>
    "use strict";
     
    //do something...
    </script>
    

    严格模式下的 javascript还对哪些行为报错了呢?

    • 禁止八进制
    "use strict";
    var x = 010;
    
    • 禁止转义字符
     "use strict";
    var x = \010; 
    
    • 禁止删除一个不能删除的属性
    "use strict";
    delete Object.prototype; 
    
    • 禁止对关键字赋值
    "use strict";
    var arguments = 3.14;    // 报错 
    

    等..

    1. 关于严格模式下的this指向问题
      原则:
      禁止this关键字指向全局对象
    function f(){
        return !this;
    } 
    f(); // 返回false,因为"this"指向全局对象,"!this"就是false
    
    function f(){ 
        "use strict";
        return !this;
    } 
    f(); // 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。
    

    由此引发的问题:
    构造函数创建实例,如果忘了加new,this不再指向全局对象,而是报错

    function f(){
        "use strict";
        this.a = 1;
    };
    f();// 报错,this未定义
    
    1. 关于严格模式的联想:
      vue源码中,使用的就是严格模式
    (function (global, factory) {
      typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
      typeof define === 'function' && define.amd ? define(factory) :
      (global = global || self, global.Vue = factory());
    }(this, function () { 'use strict';
    
    ...
    
    //Vue构造函数,不用忘记new 直接报错
    function Vue (options) {
        if (!(this instanceof Vue)
        ) {
          warn('Vue is a constructor and should be called with the `new` keyword');
        }
        this._init(options);
    }
    

    相关文章

      网友评论

          本文标题:严格模式 学习笔记

          本文链接:https://www.haomeiwen.com/subject/xgksultx.html