Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Strict Mode (Chế độ nghiêm ngặt) trong JavaScript


Strict Mode

Được giới thiệu trong ECMAScript 5. Bật bằng "use strict" ở đầu script hoặc function.

  • Chuyển silent errors thành thrown errors → debug dễ hơn.
  • Cấm biến chưa khai báo → giảm memory leak.
  • Cấm xóa property không configurable, trùng tham số hàm, v.v.

Ví dụ 1: Strict mode trong function

<html> <body> <script> myString1 = "non-strict mode allows undeclared variables"; document.write(myString1); document.write("</br>"); function myFun(){ "use strict"; var myString2 = "Strict mode allows declared variables"; document.write(myString2); } myFun(); </script> </body> </html>

Kết quả

non-strict mode allows undeclared variables Strict mode allows declared variables

Ví dụ 2: Strict mode bắt lỗi biến chưa khai báo

<html> <body> <script> myString1 = "non-strict mode allows undeclared variables"; document.write(myString1); document.write("</br>"); function myFun(){ "use strict"; myString2 = "Strict mode allows declared variables"; // LỖI: chưa khai báo document.write(myString2); } myFun(); </script> </body> </html>

Kết quả

non-strict mode allows undeclared variables

Lỗi ReferenceError: myString2 is not defined xuất hiện trong console, code sau không chạy.