ตัวอย่าง: User-defined Object Constructor
<html>
<head>
<title>User-defined objects</title>
<script>
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script>
var myBook = new book("PHP", "Amit");
book.prototype.price = null; // เพิ่ม Property ให้ Prototype
myBook.price = 250; // Set Property ให้ Instance นี้
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
ผลลัพธ์
Book title is : PHP Book author is : Amit Book price is : 250
คำอธิบาย
function book()เป็น Constructor Function (รูปแบบ ES5)this.title,this.authorเป็น Instance Propertiesbook.prototype.price = nullเพิ่ม Property ให้ Prototype (Shared)myBook.price = 250สร้าง Own Property ทับ Prototype
รูปแบบ ES6 Class (แนะนำปัจจุบัน)
class Book {
constructor(title, author, price = 0) {
this.title = title;
this.author = author;
this.price = price;
}
getInfo() {
return `${this.title} by ${this.author} - $${this.price}`;
}
}
const myBook = new Book("PHP", "Amit", 250);
console.log(myBook.title); // "PHP"
console.log(myBook.getInfo()); // "PHP by Amit - $250"
เข้าถึง Property ของ Array of Objects
const books = [
{ title: "PHP", author: "Amit", price: 250 },
{ title: "JS", author: "John", price: 300 },
{ title: "Python", author: "Jane", price: 200 }
];
// เข้าถึง Property ของ Element ตัวที่ n
console.log(books[0].title); // "PHP"
// วนลูปเข้าถึงทุกตัว
books.forEach(book => console.log(book.title, book.price));
// ดึง Property เฉพาะบางอย่าง (Map)
const titles = books.map(book => book.title); // ["PHP", "JS", "Python"]
// กรอง (Filter)
const expensive = books.filter(book => book.price > 220);
Property Access Patterns
| Pattern | Syntax | Use Case |
|---|---|---|
| Dot Notation | obj.property | Property ชื่อคงที่ Valid Identifier |
| Bracket Notation | obj['property'] | Property ชื่อไดนามิก, มี Space, Special Char |
| Destructuring | const {title, author} = obj | ดึงหลาย Property พร้อมกัน |
| Optional Chaining | obj?.property | กัน Error ตัวเป็น null/undefined (ES2020) |
สรุป
เข้าถึง Property ของ Object ใน Array: ใช้ Dot/Bracket Notation ร่วมกับ Index หรือ Iteration Methods (forEach, map, filter) รูปแบบ Class (ES6+) ชัดเจนและมี Feature มากกว่า Constructor Function แบบเก่า