DrillLab
第 29 / 105 道29 / 105 · #294

"use strict" 是干什么的

What is "use strict"

先自己答,再往下看Answer it yourself first

一句话:开启严格模式 —— 把一批「静默出错」的写法变成直接抛错, 并禁掉一些历史包袱。

具体管四件事(记两三条就够答):

  • 禁止隐式全局变量。x = 1 忘了 let, 非严格下会悄悄挂到 window, 严格下抛 ReferenceError这是它最大的价值。
  • 函数里的 thisundefined, 而不是 window—— 能让「忘了 bind」当场暴露。
  • 给只读属性赋值、删不可删的属性会抛错而不是静默失败。
  • with、禁重复参数名、arguments 不再和参数联动。

会追问:「现在还要手写吗?」—— 基本不用了ES 模块和 class 内部自动就是严格模式。 所以只有写老式 <script>或 CommonJS 时才需要手写。 能答出这条说明你知道现状。

顺带一个真实关联:这就是「Object.freeze 之后修改会抛错」的原因 —— 非严格模式下它只是静默失败。 我们的评论树那道题就是靠这个来验证不可变性的。

In one line: it switches on strict mode — a batch of things that used to fail silently now throw, and some historical baggage is banned outright.

It covers four things; two or three of them are enough to answer:

  • No implicit globals. x = 1 with a forgotten let quietly lands on window in sloppy mode, and throws ReferenceError in strict mode. This is its biggest single win.
  • this inside a plain function is undefined instead of window — so a forgotten bind throws right there.
  • Assigning to a read-only property, or deleting one that cannot be deleted, throws instead of failing silently.
  • with is banned, duplicate parameter names are banned, and arguments no longer tracks the parameters.

Follow-up: “Do you still type it by hand?” — almost never: ES modules and class bodies are strict automatically. You only write it for old-style <script> tags or CommonJS. Saying so shows you know where things stand today.

One real connection worth adding: this is why writing to an object after Object.freeze throws — in sloppy mode it just fails silently. Our comment-tree exercise leans on exactly that to verify immutability.