JavaScript 基礎
嚴格模式 (use strict) 的用途?有什麼好處?
嚴格模式('use strict')
如何啟用
在檔案頂部或函式頂部加入:
'use strict';
// 或函式內啟用
function foo() {
'use strict';
}
ES6 的
class和module預設為嚴格模式。
嚴格模式的好處
1. 防止隱式全域變數
'use strict';
x = 10; // ReferenceError:x 未宣告
2. 禁止 this 指向全域物件
'use strict';
function foo() { return this; }
foo(); // undefined(非嚴格模式為 window)
3. 禁止刪除不可刪除的屬性
'use strict';
delete Object.prototype; // TypeError
4. 禁止重複參數名稱
'use strict';
function foo(a, a) {} // SyntaxError
5. 禁止使用保留字作為變數名
'use strict';
let eval = 1; // SyntaxError
let arguments = 2; // SyntaxError
總結
嚴格模式讓 JavaScript 更安全、更容易除錯,是現代開發的最佳實踐。
✦ AI 模擬面試
輸入你的答案,AI 即時分析精準度與改進空間
登入後即可使用 AI 評分
