class กับ phototype ของ nodejs



เป็นการรวมกลุ่มของฟังก์ชันที่ทำงานภายใต้แนวการทำงานเดียวกัน คล้ายๆกับ OOP เหมือน
การสร้างฟังก์ชันหนึ่งแล้วสร้างฟังก์ชันอื่นมาผูกกับฟังก์ชันนี้  มีวิธีสร้างคือเริ่มต้นให้สร้างฟังก์ชันหนึ่ง
ก่อน  แนะนำให้ตั้งชื่อฟังก์ชันนำหน้าด้วยใหญ่เพื่อเป็นการแยกว่านี่คือ prototype ส่วนชื่อนำหน้าด้วยตัว
เล็กคือฟังก์ชันธรรมดา  ต่อมาให้ผูกฟังก์ชันด้วยคำสั่ง prototype ดังตัวอย่างโค้ดด้านล่าง    ตัวแปรของ 
prototype จะขึ้นต้นด้วย this. ฟังก์ชันที่ผูกกับ prototype จะเข้าถึงตัวแปรแบบนี้ได้ด้วย this. ตามด้วย
ชื่อตัวแปร


function Car(engine, color) {
  this.engine = engine
  this.color = color
}

Car.prototype.getEngine = function(){
  return this.engine
}

Car.prototype.setEngine = function(engine){
  this.engine = engine
}

Car.prototype.getColor = function(){
  return this.color
}

Car.prototype.setColor = function(color){
  this.color = color
}

var honda = new Car('V8 Turbo', 'Red')
console.log(honda.getEngine(), honda.getColor())
honda.setColor('Blue')
honda.setEngine('Mitsubishi')
console.log(honda.getEngine(), honda.getColor())
// output
→V8 Turbo, Red
→Mitsubishi, Blue

จากตัวอย่างข้างบน ประกาศชื่อฟังก์ชัน Car ใช้ this เป็นตัวกำหนดค่าตัวแปรของ prototype ส่วนฟังก์ชันลูกให้ประกาศ Car.prototype.some_function ส่วนตอนประกาศ object ของ prototype ใช้ new นำหน้าเหมือนประกาศ object ของ class ในภาษาอื่นเลย   คำสั่งในฟังก์ชัน Car จะทำงานก่อนเหมือน constructor ของ class เลยเช่นกัน

เนื่องจากในตอนนี้มี ES6 ที่ทำให้ javascript สามารถเขียนโค้ดเหมือนการสร้าง class ได้แล้ว
ต่อไปจะเป็นตัวอย่างโค้ดของ prototype Car ที่แปลงเป็น class ตามตัวอย่างโค้ดข้างล่างเลย


class Car {
    constructor(engine, color){
      this.engine = engine
      this.color = color       
    }

    getEngine(){
      return this.engine
    }

    setEngine(engine){
      this.engine = engine
    }

    getColo(){
      return this.color
    }

    setColor(color){
      this.color = color
    }
}

จากตัวอย่างโค้ดด้านพบมีความแตกต่างคือมี constructor ด้วยนะ  เมื่อสร้าง object ของ Car 
จะเข้ามาทำงานในฟังก์ชันนี้เป็นอันดับแรก  ส่วนฟังก์ชันอื่นๆก็ลดรูปลงมาประกาศเพียงชื่อฟังก์ชันก็พอ  
ดูแล้วปริมาณโค้ดลดลงไปพอสมควรเลยทีเดียว

ความคิดเห็น