ความแตกต่าง: Object.freeze() ป้องกัน mutability แต่ const ไม่ป้องกัน mutability
Const
Const พฤติกรรมเหมือน let ตัวแปรที่ประกาศด้วย const ไม่สามารถ reassign ได้ เป็น block scoped ไม่ใช่ function scoped อย่าง var
ข้อจำกัด: const ไม่ป้องกัน object mutability properties ของ object ยังเปลี่ยนได้แม้ประกาศด้วย const ควรหลีกเลี่ยง const เพื่อป้องกัน mutability
ตัวอย่าง
<html> <body> <script>
const person = {
"name": "Suresh",
"Country": "India",
"Designation": "Mayor"
};
person.Country = "England";
document.write(person.Country);
</script> </body> </html>
ผลลัพธ์
England
Object.freeze()
ให้ immutability object ที่ freeze แล้ว properties ไม่สามารถเปลี่ยนได้
ตัวอย่าง
<html> <body> <script>
const person = {
"name": "Suresh",
"Country": "India",
"Designation": "Mayor"
};
Object.freeze(person);
person.Country = "England";
document.write(person.Country);
</script> </body> </html>
ผลลัพธ์
India