自從改用 React Hooks 搭配 Functional Component 之後,Class 的概念都快忘光光了呢~ (也有可能是根本沒懂過?) 決定 refresh 一下 Class 如何使用。

甚麼是 Class?

class 是用來創造 Object 的。 想像成 class 是一間汽車工廠,只要給不同的零件就能生成不同型號的車。

Property 和 Method

Property

Property 用來表示 Object 內有什麼東西。 在定義 Class 之初,需要先建構一個 constructor,用來接收外部參數並指派這些參數給對應的 Property。

Method

Method 用來表示 Object 可以執行什麼動作。Method 會定義在 constructor 之後。

範例:

class Animal {
  constructor(_species, _sound){
    this.species = _species
    this.sound = _sound
  }
  makeSound(){
    return `${this.sound.toUpperCase()}!`
  }
}
const scooby = new Animal('dog','scooby-dooby-doo');
console.log(`Scooby is a ${scooby.species}`); // Scooby is a dog
console.log(`Scooby says "${scooby.makeSound()}"`) // Scooby says "SCOOBY-DOOBY-DOO!"

注意 如果在 constructor 以外的地方要使用傳進來的參數,要指派給 Property 再用 this.PropertyName 來取用喔!


參考資料: JavaScript Classes Tutorial from freecodecamp_YT

按讚的人:

共有 3 則留言

很好的分享!

歡迎繼續多多分享!

OOP 用最簡化的定義來說,就是「狀態」跟「行為」放在一起

各種程式語言實作方法不同,但核心精神不變

此外,JavaScript 的實作稱為「prototype-based」,比較特別一點

最後就是,JavaScript 社群近年比較不注重 OOP 相關的 design pattern,轉向 FP 相關 concept 與 design pattern 為主,但各種 programming paradigm 都廣泛地學習,是很好的~

👍👍👍

按讚的人: