0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript:5.オブジェクト化

Posted at

そもそもオブジェクト化とは?

「複数のバラバラの情報を1つの意味のある”もの”としてまとめる」ことで操作や管理を楽にするテクニック

今回を例にすると

食べ物(Food)という”1個の意味あるもの”が持つべき情報

element:HTMLの要素
score:数字(得点)
selected:選ばれているか?(状態)

food.ts
type FoodItem = {
    element: HTMLDivElement;
    score: number;
    selected: boolean;
}

この3つを1つのセットでFoodItemとする。
このようにまとめてオブジェクトにすることで分かりやすく安全に管理できる。
下記は具体的に情報を設定したコードである

food.ts

    element:<div class="food">...</div>,
    score:5,
    selected:false

さらにそのオブジェクトが複数あるときは下記のように配列で管理する

food.ts
const foodItems: FoodItem[] = [
  { element: ..., score: 5, selected: true },
  { element: ..., score: -3, selected: false },
  ...
];

オブジェクト化のメリット

・意味のある単位で扱える
  ⇒HTML要素・スコア・選択状態を1セットにできる
・状態の確認が楽
  ⇒item.selectedで1発でわかる
・拡張しやすい
  ⇒カテゴリ・タグ・画像...何でも後から追加可能
・不具合が起きにくい
  ⇒element[i]とscore[i]がズレる問題が起きない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?