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

ทำไมต้องใช้ "use strict" ใน JavaScript?


"use strict" เป็นคำสั่งนำทาง (directive) ซึ่งเป็นลิเทอรัลนิพจน์ (literal expression) ถูกนำเข้ามาใน JavaScript 1.8.5 ตามชื่อที่บ่งชี้ "use strict" ระบุว่าโค้ดจะถูกexecute ในโหมดเข้มงวด (strict mode)

มาประกาศ strict mode กัน เพื่อประกาศ ให้เพิ่มคีย์เวิร์ด "use strict" ไว้ตรงจุดเริ่มต้น สำหรับขอบเขตทั่วไป ให้ประกาศที่จุดเริ่มต้นของสคริปต์

<!DOCTYPE html> <html> 
    <body> 
        <p>An error would come, since you have used a variable, but forgot to declare it 
        </p> 
        <p>Press F8 to see the error.</p> 
        <script> 
            "use strict"; 
            a = 1; 
        </script> 
    </body> </html>