严格模式(strict)的学习

84 阅读2分钟

严格模式(strict)的学习

严格模式下的with语句

// 'use strict'; //  Strict mode code may not include a with statement
var mes = 'hello world!'

var info = { name: '123', age: 18, mes: 'mes info!' }

function foo() {
  // with语句: 可以形成自己的作用域
  with(info) {
    console.log(mes);
  }
}
foo()

eval()的使用

// eval()是一个全局函数
var jsString = ' var age = 18; console.log(age); '
eval(jsString) // 执行字符串的javascript代码

console.log(eval(' 2 + 1 '));
/**
 * 开发中不建议使用
 * 可读性差
 * 字符串容易被拦截篡改,安全性差
 * 效率低,经过js解释器时,js引擎不会对js的字符串代码优化
 */

开启严格模式

/**
 * ECMAScript5标准中,js提出了严格模式的概念
 * 具有限制性的js模式,使代码脱离了懒散(sloppy)模式.
 * 使用严格模式时,会以严格的方式对代码进行检测和执行
 * 1.抛出错误消除原有的 静默(silent) 错误 (例如: 123.name = '123')
 * 2.js引擎在执行代码时进行更多的优化
 * 3.禁用ECMAScript在未来版本可能定义的一些错误语法 ( let class = 'Fhup' )
 */

// 打包工具默认开启严格模式

// 开启严格模式,只针对当前文件
// 'use strict';
age = '123'
console.log(age);

// 对一个函数开启严格模式
function foo() {
  'use strict';
  true.foo = '123'
}
foo()

严格模式常见限制

'use strict';

// 1.禁止意外创建全局变量
// function foo() {
//   'use strict';
//   age = 3
// }
// foo()
// console.log(age);

// 2.不允许函数有 相同的参数名称
// function foo(x, y, x) {
//   console.log(x, y, x);
// }
// foo(1, 2, 3) // 3 2 3

// 3.静默错误
// true.class = '123'
// NaN = '123'

// 4.不允许使用原先的8进制
// var num = 0123
// 可以使用: 0o123 -> 八进制 , 0x123 -> 十六进制

// 5.with不允许使用

// 6.eval函数不会向上引用变量了 (打开严格不会在上一层作用域添加变量了)
// var jsString = ' var str = "Fhup"; console.log(str); ' // 会在全局定义str
// eval(jsString)
// console.log(str);

// 7.严格模式下的this
// 在严格模式下,只有独立函数执行(默认绑定)的this都会指向undefined,其他的this绑定正常执行
function bar() {
  console.log(this);
}
var obj = {
  name:'Fhup',
  bar : bar
}

bar() // window,独立函数调用,开启严格: this=undefined
obj.bar() // {name: 'Fhup', bar: ƒ}
var xxx = obj.bar
xxx() // window,独立函数调用,开启严格: this=undefined

// setTimeout的this
setTimeout(() => {
  console.log(this); // this 都为 window,和严格没有关系,内部实现可能是 fn.apply(window)
}, 100)