详解JavaScript中的Strict模式

作者:纸飞机时间:2026-10-24 11:53:05浏览:309

本文深入解析JavaScript ES5引入的Strict模式(严格模式)。详细阐述其启用方式,包括脚本、函数及ES6模块中的不同用法。重点分析Strict模式带来的语法与运行时变化,如强制抛出异常、简化变量与arguments使用、提升安全性以及保留关键字限制,旨在帮助开发者规范代码并避免潜在错误。

简介

ES5标准引入了Strict模式,通常被称为严格模式,相对地,常规写法被称为非严格模式。

Strict模式并非非严格模式的子集,两者在语义上存在显著差异。因此,在应用Strict模式时,必须进行严格的测试,以确保程序在严格模式下的执行效果与非严格模式保持一致。

使用Strict mode

Strict模式会改变JavaScript的部分行为表现,具体细节将在后续章节详细讲解。

首先介绍如何启用Strict mode。

Strict模式主要应用于完整的脚本文件或函数内部,不适用于代码块(block {})。如果在代码块中使用Strict mode,该模式不会生效。

此外,eval中的代码、Function构造函数生成的代码、事件处理程序属性以及传递给WindowTimers.setTimeout()的字符串,均可视为完整的脚本,在这些环境中也可以使用Strict mode。

若在script脚本中使用Strict模式,只需在脚本顶部添加"use strict"指令:


// 整个脚本的strict模式
'use strict';
var v = "Hi! I'm a strict mode script!";

同样,我们也可以在函数内部启用Strict模式:


function strict() {
  // 函数的strict模式
  'use strict';
  function nested() { return 'And so am I!'; }
  return "Hi!  I'm a strict mode function!  " + nested();
}
function notStrict() { return "I'm not strict."; }

如果使用ES6中引入的modules(模块),模块默认即处于Strict模式,无需额外添加"use strict"指令:


function myModule() {
    // 默认就是strict模式
}
export default myModule;

strict mode的新特性

Strict模式在语法和运行时行为上与非严格模式均有不同,接下来将逐一介绍这些变化。

强制抛出异常

在JavaScript中,某些操作本应报错,但因语言特性未抛出异常,导致运行结果不符合预期。

启用Strict模式后,这些操作将直接抛出异常。

例如,在Strict模式中,使用未定义的全局变量将导致错误:


'use strict';

globalVar = 10; //ReferenceError: globalVar is not defined

这有助于避免因拼写错误导致变量名写错而引发的隐蔽问题。

再看其他几个例子:


'use strict';

// 赋值给不可写的全局变量,
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError

// 赋值给不可写的属性
var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42, writable: false });
obj1.x = 9; // throws a TypeError

// 赋值给一个get方法
var obj2 = { get x() { return 17; } };
obj2.x = 5; // throws a TypeError

// 赋值给一个禁止扩展的对象
var fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = 'ohai'; // throws a TypeError

Strict模式限制删除不可删除的属性,例如构造函数的prototype属性:


'use strict';
delete Object.prototype; // throws a TypeError

禁止在对象字面量和函数参数中出现重复的属性名:


'use strict';
var o = { p: 1, p: 2 }; // Duplicate declaration

function sum(a, a, c) { // Duplicate declaration
    'use strict';
    return a + a + c;
}

禁止为基础类型设置属性:


(function() {
'use strict';

false.true = '';         // TypeError
(14).sailing = 'home';   // TypeError
'with'.you = 'far away'; // TypeError

})();

简化变量的使用

使用Strict模式可以简化变量使用规则,增强代码的可读性。

首先,Strict模式禁止使用with语句。

with语句功能强大,通过将对象传递给with,可以影响变量查找的作用域链。即在with块中访问属性时,除了在当前作用域链中查找,还会在with传递的对象中查找。


with (expression)
  statement

使用with通常是为了简化代码,例如:


var a, x, y;
var r = 10;

with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}

上述例子中,PI是Math对象的属性,但在with块中可以直接使用,类似于Java中的import语句。

以下示例展示了with在使用中可能存在的问题:


function f(x, o) {
  with (o) {
    console.log(x);
  }
}

在with块中输出x变量,从代码看f函数传入了x变量。但如果with使用的对象中也存在x属性,就会产生意想不到的结果。

因此,在Strict模式中,禁止使用with语句。

其次是对eval函数的改动。

在非严格模式中,eval中定义的变量会自动加入到包含eval的作用域中。看一个例子:


var x = 17;
var evalX = eval("var x = 42; x;");
console.log(x);

由于eval引入了新变量x,其值覆盖了最初定义的x=17,最终结果为42。

如果启用use strict,eval中的变量不会加入到现有作用域中,最终结果为17。


var x = 17;
var evalX = eval("'use strict'; var x = 42; x;");
console.log(x);

这样做的好处是避免eval对现有程序逻辑产生意外影响。

在Strict模式下,也不允许delete name操作:


'use strict';

var x;
delete x; // !!! syntax error

eval('var y; delete y;'); // !!! syntax error~~

简化arguments对象

在JavaScript中,arguments代表参数数组。在Strict模式下,arguments不能作为变量名被赋值:


'use strict';
arguments++;
var obj = { set p(arguments) { } };
try { } catch (arguments) { }
function arguments() { }
var f = new Function('arguments', "'use strict'; return 17;");

上述操作均会报错。

另外,在普通模式下,arguments与命名参数是绑定的,arguments[0]和arg同步变化,均表示第一个参数。

但在Strict模式下,arguments表示实际传入的参数。

举个例子:


function f(a) {
    a = 42;
    return [a, arguments[0]];
}
var pair = f(17);
console.log(pair[0]);  // 42
console.log(pair[1]);  // 42

上述例子中,arguments[0]与命名参数a绑定,无论f传入什么值,arguments[0]的值最终都是42。

如果切换到Strict模式:


function f(a) {
    'use strict';
    a = 42;
    return [a, arguments[0]];
}
var pair = f(17);
console.log(pair[0]); // 42
console.log(pair[1]);  // 17

在此模式下,arguments[0]接收实际传入的参数,最终结果为17。

在Strict模式下,禁止使用arguments.callee。通常arguments.callee指向当前执行的函数,这会阻碍虚拟机对内联函数的优化,因此在Strict模式下被禁止。

让JavaScript变得更加安全

在普通模式下,若在函数f()中调用this,this指向全局对象。在Strict模式下,该this的值为undefined。

如果通过call或apply调用,传入primitive value(基础类型)时,在普通模式下this会自动指向其Box类(基础类型对应的Object类型,如Boolean、Number等)。如果传入undefined或null,this指向全局对象。

而在Strict模式下,this指向传入的值,不会进行转换或变形。

以下断言均为true:


'use strict';
function fun() { return this; }
console.assert(fun() === undefined);
console.assert(fun.call(2) === 2);
console.assert(fun.apply(null) === null);
console.assert(fun.call(undefined) === undefined);
console.assert(fun.bind(true)() === true);

为何这样更安全?这意味着在Strict模式下,无法通过this指向window对象,从而保障了程序的安全性。

另外,在普通模式下,可以通过fun.caller或fun.arguments获取函数的调用者和参数,这可能导致访问私有属性或不安全变量,造成安全隐患。

在Strict模式下,禁止使用fun.caller或fun.arguments。


function restricted() {
  'use strict';
  restricted.caller;    // throws a TypeError
  restricted.arguments; // throws a TypeError
}
function privilegedInvoker() {
  return restricted();
}
privilegedInvoker();

保留关键字和function的位置

为保证JS标准的后续发展,Strict模式中禁止使用关键字作为变量名,这些关键字包括implements、interface、let、package、private、protected、public、static和yield等。


function package(protected) { // !!!
  'use strict';
  var implements; // !!!

  interface: // !!!
  while (true) {
    break interface; // !!!
  }

  function private() { } // !!!
}
function fun(static) { 'use strict'; } // !!!

对于function,在普通模式下可以在任何位置定义,但在Strict模式下,function的定义只能在脚本顶层或函数内部定义:


'use strict';
if (true) {
  function f() { } // !!! syntax error
  f();
}

for (var i = 0; i < 5; i++) {
  function f2() { } // !!! syntax error
  f2();
}

function baz() { // kosher
  function eit() { } // also kosher
}

总结

Strict模式对JS的后续发展和现有编程模式的规范起到了重要作用。但在浏览器端使用时,仍需注意浏览器兼容性,并做好严格测试。

以上就是详解javascript中的Strict模式的详细内容,更多关于javascript中的Strict模式的资料请关注本站其它相关文章!

作者最新文章