严格模式 学习笔记

2021-07-01  本文已影响0人  squidbrother
  1. 什么是严格模式
    严格模式是ECMAScript5中新增的,用于严苛规范javascript脚本执行的模式

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

"use strict";
eval ("var x = 2"); // eval() 创建的变量不能被调用:
alert (x);     
"use strict";
x = 3.14;                // 报错 (x 未定义) 
  1. 严格模式怎么用,需要注意什么
<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);
}
上一篇 下一篇

猜你喜欢

热点阅读