Dưới đây là mã để thêm thuộc tính và phương thức vào đối tượng hiện có trong JavaScript.
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Add props methods</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>Thêm thuộc tính và phương thức vào đối tượng hiện có trong JavaScript</h1> <div class="result"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để thêm property và method cho student object và hiển thị</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let student = { }; BtnEle.addEventListener("click", () => { student.name = 'Rohan Sharma'; student.age = 16; student.place = 'Delhi'; student.displayInfo = function(){ return 'Name = '+this.name+' : Age = '+this.age+' : Place = '+this.place; } resEle.innerHTML += student.displayInfo(); }); </script> </body> </html>
Kết quả
Khi nhấn nút: Name = Rohan Sharma : Age = 16 : Place = Delhi
JavaScript cho phép thêm/xóa thuộc tính và phương thức vào object bất kỳ lúc nào (dynamic). student.displayInfo gán function expression làm method. Có thể dùng Object.defineProperty để kiểm soát enumerable, configurable, writable.