Trong ES6, nếu tên key của đối tượng trùng với tên biến truyền làm giá trị, ta có thể bỏ tên giá trị, chỉ viết tên key.
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Property Shorthands</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>Viết tắt thuộc tính ES6 trong JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để hiển thị đối tượng person</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let name='Rohan',age=16,place='Delhi'; let person = { name,age,place, } BtnEle.addEventListener("click", () => { resEle.innerHTML = 'person.name = '+person.name+'<br>'; resEle.innerHTML += 'person.age = '+person.age+'<br>'; resEle.innerHTML += 'person.place = '+person.place+'<br>'; }); </script> </body> </html>
Kết quả
Khi nhấn nút:
- person.name = Rohan
- person.age = 16
- person.place = Delhi
Cú pháp { name, age, place } tương đương { name: name, age: age, place: place }. Rất phổ biến khi tạo object từ các biến cục bộ hoặc destructuring.