ใน JavaScript มีหลายวิธีตรวจสอบว่าอ็อบเจกต์มีพร็อพเพอร์ตี้หรือไม่: obj.hasOwnProperty(prop), prop in obj, Object.hasOwn(obj, prop) (ES2022) แต่ละอย่างมีความแตกต่างเล็กน้อย
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Check Property in Object</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>ตรวจสอบ Property ใน Object ด้วย JavaScript</h1>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อตรวจสอบว่า obj มี property firstName หรือไม่</h3>
<script>
const resEle = document.querySelector(".result");
const obj = { firstName: "Rohan", lastName: "Sharma", age: 21 };
document.querySelector(".Btn").addEventListener("click", () => {
// วิธีที่แนะนำ (ES2022)
if (Object.hasOwn(obj, "firstName")) {
resEle.textContent = "มี firstName (Object.hasOwn)";
} else {
resEle.textContent = "ไม่มี firstName";
}
// วิธีเก่า
// if (obj.hasOwnProperty("firstName")) { ... }
// if ("firstName" in obj) { ... }
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

เปรียบเทียบ 3 วิธีหลัก
| วิธี | Syntax | ตรวจสอบ Own Property | ตรวจสอบ Prototype Chain | ปลอดภัยกับ null/undefined |
|---|---|---|---|---|
| Object.hasOwn() (ES2022) | Object.hasOwn(obj, "prop") | ✅ | ❌ | ✅ (คืน false) |
| hasOwnProperty() | obj.hasOwnProperty("prop") | ✅ | ❌ | ❌ (โยน Error ถ้า obj เป็น null) |
| in operator | "prop" in obj | ❌ | ✅ | ❌ (โยน Error ถ้า obj เป็น null) |
ตัวอย่างความแตกต่าง
const parent = { inherited: "from parent" };
const child = Object.create(parent);
child.own = "mine";
console.log(Object.hasOwn(child, "own")); // true
console.log(Object.hasOwn(child, "inherited")); // false
console.log("inherited" in child); // true (พบใน prototype)
console.log(child.hasOwnProperty("inherited")); // false
// ปัญหา hasOwnProperty
const obj = Object.create(null); // ไม่มี prototype
// obj.hasOwnProperty("x"); // TypeError: hasOwnProperty is not a function
console.log(Object.hasOwn(obj, "x")); // false (ปลอดภัย)
// ปัญหา in operator
console.log("toString" in {}); // true (มาจาก Object.prototype)
แนวทางปฏิบัติที่ดีที่สุด
- ใช้ Object.hasOwn(obj, prop) (ES2022) — มาตรฐานใหม่ ปลอดภัย สะดวก
- รองรับ Browser: Chrome 93+, Firefox 92+, Safari 15.4+, Edge 93+
- Polyfill สำหรับเก่า:
Object.hasOwn = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop); - ใช้
inเฉพาะต้องการตรวจสอบ prototype chain (เช่น interface checking) - หลีกเลี่ยง
obj.prop !== undefined— ค่าอาจเป็นundefinedจริงๆ
การวนลูปเฉพาะ Own Properties
for (const key of Object.keys(obj)) { ... } // enumerable own keys
for (const key of Object.getOwnPropertyNames(obj)) { ... } // all own keys (incl non-enumerable)
for (const key of Reflect.ownKeys(obj)) { ... } // all own keys (incl Symbols)