JS class syntax

4 mins read

Published

13 January, 2021

Language

Thai

Written by

Share

JS class syntax

เชื่อว่าหลายๆคนที่เขียน javascript กันมา คงต้องเคยสงสัยกันบ้าง ว่า class ที่อยู่ใน js เนี่ย มันคืออะไร แล้วมันมีหน้าที่ต่างกับการประกาศ function อย่างไร? 

เรามารู้จักกับ class ให้มากขึ้นกันดีกว่า class เปรียบเสมือนกับ blueprint หรือแบบพิมพ์เขียว ที่สามารถนำไปสร้างเป็นสิ่งของ( object ) ตาม  blueprint หรือแบบพิมพ์เขียว( class ) นั้นๆได้ โดยภายใน class เรานั้น จะมีการตั้งค่าเริ่มต้นหรือ constructor เพื่อให้เป็นการทำงานเริ่มต้นของการสร้าง object หนึ่ง หน้าตาในการเรียกใช้งานจะคล้ายๆกับ การประกาศเรียกใช้ ฟังชันท์เลย โดยมีการเพิ่ม new ต่อหน้า เช่น 
class example { }  // สำหรับการประกาศ classconst objectExample = new example()  // สำหรับการประกาศเรียกใช้งานโดยการทำงานของ class นั้นเมื่อมีการเรียก  การสร้าง class ขึ้น ตัว class จะมองหา constructor ภายใน class เป็นตัวแรกเสมอ 

พูดให้เข้าใจง่ายๆ คือ หากเราต้องการส่ง parameter ให้กับ class เหมือนกับ function ก็เพียงต้องมี constructor ใน class เสมอ ดังตัวอย่างนี้

class exampleWithConstructor {  // การประกาศ class โดยมี constructor     constructor(param) {         this.param = param;        } } // ประกาศการใช้งาน class โดยส่ง param const objectExampleWithConstructor = exampleWithConstructor('test') 

และเมื่อเราลอง console.log( objectExampleWithConstructor ) ออกมาดูจะเห็นว่า

สิ่งที่ออกมามันคือ Object type ที่มี attributes ตามใน constructor ที่เราสร้่างไว้และมี prototype ( __proto__ ) เป็น class 
ที่เราสร้างไว้ โดยถ้าเราสร้าง Method ไว้ภายใน object ด้วยเมื่อลอง console.log ดูอีกที ภายใน prototype ( __proto__ ) ก็จะมี method ที่เราเพิ่งสร้างไว้ เช่น

class exampleWithConstructor {  // การประกาศ class โดยมี constructor    constructor(param){      this.param = param;        }}
exampleMethod() {  // สร้าง method ใน class    console.log('enter method')}
const objectExampleWithConstructor = exampleWithConstructor('test') 
objectExampleWithConstructor.exampleMethod()  // เรียกใช้งาน method ที่เราสร้างไว้

โดยเมื่อเรานำมาเทียบกับ การประกาศ function ปกติๆ เราจะไม่สามารถมาสร้าง โครงสร้างอะไรแบบนี้ได้เลย และ class ยังมีลูกเล่นให้ใช้งานอีกมากมาย เช่น การ inherit การ binding โดยสามารถนำมาสร้างโครงสร้างของ Object ที่เราต้องการได้ตามใจชอบ

อย่างที่เรารู้ๆกันดีกว่า javascript ทุกๆอย่าง คือ Object ไม่ว่าจะเป็น ค่า type Null หรือ type Array ที่เราใช้กัน จริงๆแล้วนั้น เป็น object base ของ JS ที่ built-in ขึ้นมา สามารถทดสอบได้โดยการ console.log(typeof Array กับ Null ) ได้เลยครับ

Written by
default user avatar
Senna Labs

Share

Keep me posted
to follow product news, latest in technology, solutions, and updates

More than 120,000 people/day  visit to read our blogs

Contact Senna Labs at :

hello@sennalabs.com28/11 Soi Ruamrudee, Lumphini, Pathumwan, Bangkok 10330+66 62 389 4599
© 2022 Senna Labs Co., Ltd.All rights reserved. | Privacy policy