Strict Mode ('use strict')
โหมดเข้มงวดของ ECMAScript 5 ทำให้ JavaScript:
- Throw Error แทน Silent Fail
- ป้องกัน Accidental Globals
- ปิดการใช้งาน Features ที่ Deprecated/Unsafe
- Optimize Engine ได้ดีขึ้น
การเปิดใช้งาน
// ทั้ง Script
'use strict';
// หรือใน Function
function myFunc() {
'use strict';
// ...
}
ตัวอย่าง 1: ไม่มี Strict Mode (Global)
<script>
myString1 = 'non-strict allows undeclared';
document.write(myString1);
function myFun() {
'use strict';
var myString2 = 'strict allows declared';
document.write(myString2);
}
myFun();
</script>
ผลลัพธ์: ทำงานได้ทั้งคู่ (Global ไม่ Strict, Function Strict)
ตัวอย่าง 2: มี Strict Mode ใน Function แต่ Variable ไม่ได้ประกาศ
<script>
function myFun() {
'use strict';
myString2 = 'strict mode error'; // ReferenceError!
document.write(myString2);
}
myFun();
</script>
ผลลัพธ์: ReferenceError: myString2 is not defined (ใน Console)
สิ่งที่ Strict Mode ห้าม/เปลี่ยน
| Feature | Normal | Strict |
|---|---|---|
| Undeclared Assignment | Global Var | ReferenceError |
| Delete Variable/Function | Silent Fail | SyntaxError |
| Duplicate Parameter | Allowed | SyntaxError |
| Octal Literal | Allowed | SyntaxError |
| this in Function | Global/Window | undefined |
| with Statement | Allowed | SyntaxError |
Best Practice
- ใช้
'use strict'ทุกไฟล์/โมดูล (ES Modules Default Strict) - รวมกับ Linter (ESLint) เพื่อ잡 Error ตั้งแต่ Dev Time