DEV Community

hambalee
hambalee

Posted on

7 2

JavaScript Class อธิบายพร้อมตัวอย่างโค้ด

Video ใน YouTube อธิบายแนวคิดของ class และ object เป็นภาษาไทย


ที่มา : https://youtu.be/CC4mX2fOHtI

ตัวอย่างโค้ด



class Human {
  constructor() {
    this.gender = "M"
  }

  printGender() {
    console.log(this.gender)
  }
}

class Person extends Human {
  constructor() {
    super()
    this.name = 'A'
  }

  printName() {
    console.log(this.name)
  }
}

const p = new Person()
p.printName()
p.printGender()


Enter fullscreen mode Exit fullscreen mode

ผลลัพธ์



"A" 
"M"


Enter fullscreen mode Exit fullscreen mode

อธิบายโค้ด

extends คือการสืบทอด สามารถใช้ตัวแปรหรือฟังก์ชันจากคลาสที่เราต้องการสืบทอด
ในตัวอย่างโค้ด คลาส Person สืบทอดมาจาก คลาส Human

ดังนั้น object ที่ถูกสร้างขึ้นด้วยคลาส Person จะสามารถเรียกใช้ตัวแปรหรือฟังก์ชันที่มาจากคลาส Human ได้ด้วย

const p = new Person() เป็นการสร้าง object ชื่อ p จากคลาสที่ชื่อ Person

และถ้าต้องการเปลี่ยนแปลงค่าบางอย่างก็สามารถทำได้เช่นกัน
ตัวอย่างเช่น ต้องการเปลี่ยน Gender จาก M เป็น F สามารถเขียนได้ดังนี้



//ในคลาส Person
...
  constructor() {
    super()
    this.name = 'A'
    this.gender = 'F'
  }
...


Enter fullscreen mode Exit fullscreen mode

ใน JavaScript ES7 จะสามารถทำให้กระชับได้โดย
ไม่จำเป็นต้องใส่ constructor
ใส่ตัวแปร หรือ Property ได้เลย
ไม่จำเป็นต้องเรียกใช้ super()
เปลี่ยนให้เป็น Arrow Function

จะได้โค้ดที่สั้นขึ้นดังนี้



class Human {
  gender = "M" //ไม่ต้องใส่ this 

  printGender = () => {
    console.log(this.gender) //ยังมี this อยู่
  }
}

class Person extends Human {
  name = 'A'

  printName = () => {
    console.log(this.name)
  }
}

const p = new Person()
p.printName()
p.printGender()


Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series