Có 2 cách chính để kiểm tra thuộc tính trong object, khác nhau ở việc có kiểm tra thuộc tính kế thừa (inherited) hay không.
1. Toán tử 'in' — Kiểm tra cả thuộc tính riêng và kế thừa
'tenKey' in doiTuong; // true / false
Ví dụ
<script>
const employee = { name: "Ranjan", age: 25 };
document.write('name' in employee); // true (thuộc tính riêng)
document.write('<br>');
document.write('salary' in employee); // false
document.write('<br>');
document.write('toString' in employee); // true (kế thừa từ Object.prototype)
</script>
2. hasOwnProperty() — Chỉ kiểm tra thuộc tính riêng
doiTuong.hasOwnProperty('tenKey'); // true / false
Ví dụ
<script>
const employee = { name: "Ranjan", age: 25 };
document.write(employee.hasOwnProperty('name')); // true
document.write('<br>');
document.write(employee.hasOwnProperty('salary')); // false
document.write('<br>');
document.write(employee.hasOwnProperty('toString')); // false (kế thừa)
</script>
Cách hiện đại: Object.hasOwn() (ES2022)
An toàn hơn hasOwnProperty (tránh lỗi khi object bị ghi đè phương thức).
Object.hasOwn(employee, 'name'); // true
Object.hasOwn(employee, 'toString'); // false
So sánh nhanh
| Phương pháp | Kiểm tra own property | Kiểm tra inherited | An toàn |
|---|---|---|---|
in | Có | Có | Có |
hasOwnProperty | Có | Không | Có (trừ khi bị shadow) |
Object.hasOwn() | Có | Không | Cao nhất |
Khi nào dùng cái nào?
- Cần biết key có tồn tại ở đâu (kể cả prototype) →
in. - Chỉ quan tâm key do dev định nghĩa →
Object.hasOwn()(ưu tiên) hoặchasOwnProperty().