Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Strict Mode ใน JavaScript: การเข้มงวดโค้ดและป้องกันข้อผิดพลาด

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 ห้าม/เปลี่ยน

FeatureNormalStrict
Undeclared AssignmentGlobal VarReferenceError
Delete Variable/FunctionSilent FailSyntaxError
Duplicate ParameterAllowedSyntaxError
Octal LiteralAllowedSyntaxError
this in FunctionGlobal/Windowundefined
with StatementAllowedSyntaxError

Best Practice

  • ใช้ 'use strict' ทุกไฟล์/โมดูล (ES Modules Default Strict)
  • รวมกับ Linter (ESLint) เพื่อ잡 Error ตั้งแต่ Dev Time