บทนำ
JavaScript ไม่มีโครงสร้าง Struct แบบ C/C++ หรือ Go ในตัว แต่สามารถจำลองพฤติกรรมคล้าย Struct ได้โดยใช้ Object และ Constructor Function
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<script>
function displayStruct(str) {
var str = str.split(' ');
var count = str.length;
function constructor() {
for (var i = 0; i < count; i++) {
this[str[i]] = arguments[i];
}
}
return constructor;
}
var Item = displayStruct("player country");
var res = new Item('Sachin', 'India');
alert("Country: " + res.country);
</script>
</body>
</html>
คำอธิบายโค้ด
- displayStruct(str) - ฟังก์ชันรับ string ชื่อฟิลด์ คั่นด้วย space
- str.split(' ') - แยกเป็น array:
["player", "country"] - constructor() - ฟังก์ชันสร้าง object กำหนด property ตามชื่อฟิลด์
- arguments[i] - ค่าที่ส่งเข้ามาตอน new Item()
- new Item('Sachin', 'India') - สร้าง instance มี player="Sachin", country="India"
วิธีสมัยใหม่ (Modern Approach)
1. Class Syntax (ES6+)
class Item {
constructor(player, country) {
this.player = player;
this.country = country;
}
}
const res = new Item('Sachin', 'India');
console.log(res.country); // "India"
2. Object Literal / Factory Function
function createItem(player, country) {
return { player, country };
}
const res = createItem('Sachin', 'India');
3. Object.create()
const ItemProto = {
getInfo() {
return `${this.player} from ${this.country}`;
}
};
const res = Object.create(ItemProto);
res.player = 'Sachin';
res.country = 'India';
4. TypeScript Interface (Type Safety)
interface Item {
player: string;
country: string;
}
const item: Item = { player: 'Sachin', country: 'India' };
เปรียบเทียบ
| วิธี | ข้อดี | ข้อเสีย |
|---|---|---|
| Class | อ่านง่าย, มี methods, extends ได้ | ต้องใช้ ES6+ |
| Factory Function | ง่าย, ไม่ต้อง new, closure ได้ | ไม่มี prototype chain |
| Object.create | ควบคุม prototype ได้เต็มที่ | ซับซ้อนกว่า |
| TypeScript | Type safety, IDE support | ต้อง compile |