JavaScript Objects เป็น Dynamic - สามารถเพิ่ม/แก้ไข/ลบ Properties ได้ตลอดเวลา รันไทม์ (Runtime) ทำให้ยืดหยุ่นมากสำหรับการจัดการข้อมูล
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dynamic Object Values</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>ตั้งค่า JavaScript Object Values แบบ Dynamic</h1>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>คลิกปุ่มด้านบนเพื่อตั้งค่า Student Object แบบ Dynamic</h3>
<script>
const resEle = document.querySelector(".result");
const BtnEle = document.querySelector(".Btn");
let student = {
name: "Rohan",
age: 22,
displayInfo() {
return `Name = ${this.name} : Age = ${this.age}<br>`;
}
};
BtnEle.addEventListener("click", () => {
resEle.innerHTML = student.displayInfo();
resEle.innerHTML += "<br>หลังจากเปลี่ยน Properties<br>";
// Dynamic Property Assignment
student.name = "Shawn";
student.age = 19;
student.grade = "A"; // เพิ่ม Property ใหม่
resEle.innerHTML += student.displayInfo();
});
</script>
</body>
</html>
วิธี Dynamic Property Access
const obj = { name: "John" };
// 1. Dot Notation (Static Key)
obj.age = 30;
// 2. Bracket Notation (Dynamic Key)
const key = "email";
obj[key] = "john@example.com";
// 3. Computed Property Names (ES6)
const dynamicKey = "phone";
const obj2 = {
name: "Jane",
[dynamicKey]: "123-456-7890"
};
// 4. Object.defineProperty (Advanced Control)
Object.defineProperty(obj, "secret", {
value: "hidden",
writable: false, // ไม่ให้เปลี่ยนค่า
enumerable: false, // ไม่แสดงใน for...in, Object.keys
configurable: false // ไม่ให้ลบ/เปลี่ยน Config
});
Dynamic Object Patterns
// 1. Form Data to Object
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// 2. Dynamic Key từ Variable/Input
function setField(obj, field, value) {
obj[field] = value;
return obj;
}
// 3. Merge Dynamic Properties
const base = { id: 1 };
const dynamic = { name: "John", [getDynamicKey()]: "value" };
const merged = { ...base, ...dynamic };
// 4. Proxy (Intercept Operations)
const handler = {
set(target, prop, value) {
console.log(`Setting ${prop} = ${value}`);
target[prop] = value;
return true;
}
};
const proxy = new Proxy({}, handler);
proxy.dynamic = "works";
ผลลัพธ์
ก่อน: Name = Rohan : Age = 22
หลัง: Name = Shawn : Age = 19 (และมี grade = "A" เพิ่มเข้ามา)