JavaScriptにおける実用的なカプセル化手法

オブジェクト生成のファクトリ関数

構造が類似した複数のオブジェクトを生成する場合、ファクトリ関数を利用します。

function generateProduct(name, price) {
  return {
    productName: name,
    unitPrice: price,
    displayInfo() {
      return `製品名: ${this.productName}, 価格: ${this.unitPrice}円`;
    }
  };
}

const itemA = generateProduct("ワイヤレスイヤホン", 9800);
console.log(itemA.displayInfo());

クロージャによる状態管理

内部状態を外部から直接変更できないようにするには、クロージャを活用します。

function createThermometer() {
  let currentTemp = 25;

  return {
    increase() {
      currentTemp++;
      console.log(`現在の温度: ${currentTemp}℃`);
    },
    getTemperature() {
      return currentTemp;
    }
  };
}

const roomThermo = createThermometer();
roomThermo.increase();

クラスを用いたカプセル化

オブジェクト指向プログラミングに適したクラスベースのアプローチです。

class MobileDevice {
  constructor(brand, model) {
    this.deviceBrand = brand;
    this.deviceModel = model;
    this.batteryLevel = 100;
  }

  useBattery(power) {
    this.batteryLevel -= power;
    console.log(
      `${this.deviceBrand} ${this.deviceModel} バッテリー残量: ${this.batteryLevel}%`
    );
  }
}

const myPhone = new MobileDevice("Google", "Pixel");
myPhone.useBattery(15);

高階関数による処理の抽象化

関数を引数に取る高階関数で、共通処理と可変処理を分離します。

function transformArray(arr, processor) {
  const output = [];
  for (const element of arr) {
    output.push(processor(element));
  }
  return output;
}

const values = [5, 10, 15];
const tripled = transformArray(values, x => x * 3);
console.log(tripled);

カリー化による関数の特殊化

複数引数の関数を単一引数関数のチェーンに変換し、パラメータを固定します。

const generateLogger = category => message => {
  console.log(`[${category}] ${new Date().toISOString()}: ${message}`);
};

const debugLog = generateLogger("DEBUG");
debugLog("処理を開始します");

関数合成による処理の連結

単純な関数を組み合わせて複雑な処理を構築します。

const addSuffix = text => `${text}さん`;
const capitalize = str => str.toUpperCase();

const processName = original => addSuffix(capitalize(original));
console.log(processName("yamada"));

オブジェクトの複製手法

オブジェクトのコピーには浅いコピーと深いコピーの区別があります。

// 浅いコピー
const source = { id: 1, config: { theme: "dark" } };
const shallowCopy = { ...source };

// 深いコピー
const deepCopy = JSON.parse(JSON.stringify(source));

タグ: javascript カプセル化 ファクトリパターン クロージャ クラス

6月12日 22:07 投稿