JavaScript Object cho phép thao tác động (dynamic) các thuộc tính (properties) và phương thức (methods) tại runtime.
1. Thêm/ Cập nhật thuộc tính
// Dot notation (key hợp lệ identifier)
obj.newProp = value;
obj["newProp"] = value;
// Bracket notation (key bất kỳ string, biến, expression)
const key = "dynamic";
obj[key] = value;
obj["key with spaces"] = value;
2. Truy cập thuộc tính
obj.prop; // Dot notation
obj["prop"]; // Bracket notation
obj[key]; // Biến key
obj?.prop; // Optional chaining (ES2020) - an toàn nếu obj null/undefined
3. Xóa thuộc tính
delete obj.prop; // true/false (thành công/thất bại)
delete obj["prop"]; // Cú pháp bracket
// Chỉ xóa own property, không xóa inherited property
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Object Properties CRUD</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.result { font-size: 18px; font-weight: 500; margin: 10px 0; color: green; }
button { padding: 8px 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>Thêm, Truy cập, Xóa thuộc tính Object JS</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result"></div>
<button class="Btn" id="btn">THỰC HIỆN</button>
<h3> Nhấn nút để thêm, truy cập, xóa thuộc tính </h3>
<script>
const sampleEle = document.querySelector("#sample");
const resEle = document.querySelector("#result");
const obj = {
firstName: 'Rohan',
lastName: 'Sharma',
age: 22
};
sampleEle.innerHTML = "Object ban đầu: " + JSON.stringify(obj);
document.querySelector("#btn").addEventListener("click", () => {
// 1. THÊM thuộc tính mới
obj.school = 'Ryan International';
resEle.innerHTML = 'Thêm property school: ' + obj.school + '
';
// 2. TRUY CẬP thuộc tính
resEle.innerHTML += 'Truy cập obj.firstName: ' + obj.firstName + '
';
resEle.innerHTML += 'Truy cập obj["lastName"]: ' + obj["lastName"] + '
';
// 3. XÓA thuộc tính
delete obj.firstName;
resEle.innerHTML += 'Sau delete firstName: ' + obj.firstName + '
'; // undefined
resEle.innerHTML += 'Object hiện tại: ' + JSON.stringify(obj) + '
';
// 4. Kiểm tra tồn tại
resEle.innerHTML += '
Kiểm tra tồn tại:
';
resEle.innerHTML += "'firstName' in obj: " + ('firstName' in obj) + '
'; // false
resEle.innerHTML += "'age' in obj: " + ('age' in obj) + '
'; // true
resEle.innerHTML += "obj.hasOwnProperty('age'): " + obj.hasOwnProperty('age') + '
';
});
</script>
</body>
</html>
Kết quả
Object ban đầu: {"firstName":"Rohan","lastName":"Sharma","age":22}
Thêm property school: Ryan International
Truy cập obj.firstName: Rohan
Truy cập obj["lastName"]: Sharma
Sau delete firstName: undefined
Object hiện tại: {"lastName":"Sharma","age":22,"school":"Ryan International"}
Kiểm tra tồn tại:
'firstName' in obj: false
'age' in obj: true
obj.hasOwnProperty('age'): true
Phương thức kiểm tra thuộc tính:
| Phương pháp | Cú pháp | Kiểm tra own property | Kiểm tra inherited |
|---|---|---|---|
in operator | "key" in obj | ✅ | ✅ |
| hasOwnProperty | obj.hasOwnProperty("key") | ✅ | ❌ |
| Object.hasOwn (ES2022) | Object.hasOwn(obj, "key") | ✅ | ❌ |
| Undefined check | obj.key !== undefined | ⚠️ Sai nếu value = undefined | ⚠️ |
Lưu ý quan trọng:
deletechỉ xóa own property, không ảnh hưởng prototype chaindeletetrả vềtruenếu thành công,falsenếu không xóa được (non-configurable)- Không thể xóa biến khai báo
var/let/const(non-configurable) - Xóa property làm chậm object (hidden class change) - tránh trong hot path
Object.freeze() / seal() - Bảo vệ object:
const obj = { a: 1 };
Object.freeze(obj); // Không thêm/sửa/xóa được bất kỳ property nào
Object.seal(obj); // Không thêm/xóa, nhưng SỬA được value existing
Object.preventExtensions(obj); // Không thêm mới, nhưng sửa/xóa được existing