Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การทำงานกับ Structs ใน JavaScript

บทนำ

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>

คำอธิบายโค้ด

  1. displayStruct(str) - ฟังก์ชันรับ string ชื่อฟิลด์ คั่นด้วย space
  2. str.split(' ') - แยกเป็น array: ["player", "country"]
  3. constructor() - ฟังก์ชันสร้าง object กำหนด property ตามชื่อฟิลด์
  4. arguments[i] - ค่าที่ส่งเข้ามาตอน new Item()
  5. 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 ได้เต็มที่ซับซ้อนกว่า
TypeScriptType safety, IDE supportต้อง compile