"use strict" 是干什么的
What is "use strict"
一句话:开启严格模式 —— 把一批「静默出错」的写法变成直接抛错, 并禁掉一些历史包袱。
具体管四件事(记两三条就够答):
- 禁止隐式全局变量。
x = 1忘了let, 非严格下会悄悄挂到window, 严格下抛ReferenceError。这是它最大的价值。 - 函数里的
this是undefined, 而不是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 = 1with a forgottenletquietly lands onwindowin sloppy mode, and throwsReferenceErrorin strict mode. This is its biggest single win. thisinside a plain function isundefinedinstead ofwindow— 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.
withis banned, duplicate parameter names are banned, andargumentsno 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.