ES6中"use strict"是否仍保持原有工作方式?其现状与替代方案咨询
Great questions—let's unpack them clearly, since strict mode is still a key part of modern JS development even with ES6's new features.
Does "use strict" retain its original behavior in ES6?
Absolutely. ES6 fully preserves all core strict mode mechanisms from ES5. It still:
- Throws errors for undeclared variable assignments (no more accidental global variables)
- Blocks deletion of non-deletable properties (like
delete Object.prototype) - Prohibits duplicate parameter names in functions (e.g.,
function foo(a, a) {}throws an error) - Disallows problematic
withstatements - Sets
thistoundefinedin standalone function calls (instead of defaulting to the global object)
For example, this code will throw a ReferenceError in ES6 just like it did in ES5:
function doSomething() { "use strict"; accidentalGlobal = "oops"; // Error: accidentalGlobal is not defined }
A key ES6 detail: Modules (files using import/export) automatically enable strict mode, no explicit "use strict" needed.
Is "use strict" still commonly used in ES6?
It depends on your project setup:
- In ES modules: No, manual declaration is almost never needed—strict mode is enabled by default.
- In non-module scripts/CommonJS files: Yes, it’s still widely used. For traditional script tags without
type="module", or CommonJS modules (common in older Node.js setups), adding"use strict"at the top is a standard practice to avoid global scope pollution and enforce safer coding. - Legacy/mixed environments: Projects supporting older engines or mixing ES6 with ES5 often rely on explicit strict mode to maintain consistency.
Are there better alternatives to achieve its functionality?
Yes, ES6 and modern tools offer alternatives that make explicit strict mode unnecessary in many cases:
- ES Modules: Beyond automatic strict mode, modules isolate code into their own scopes, solving the global pollution problem that made strict mode critical in the first place.
- ES6 Classes: All code inside ES6 classes runs in strict mode by default—no need to add
"use strict"inside methods or constructors. - TypeScript: Its default strict compiler options go far beyond
"use strict", enforcing type safety, catching undeclared variables, and adding extra safeguards that make explicit strict mode redundant (though TypeScript still respects it if included).
That said, in non-module, non-class environments (like simple scripts), "use strict" remains a lightweight, universally supported way to enforce safe practices—there’s no better alternative for that specific context.
内容的提问来源于stack exchange,提问作者Srishti Ganjoo

