Skip to content

オブジェクトとデータ構造

ゲッターとセッターを使用する

オブジェクトのプロパティに直接アクセスするよりも、ゲッターとセッターを使用してデータにアクセスする方が優れています。「なぜか?」と疑問に思うかもしれません。以下にその理由をまとまりなく列挙します:

  • オブジェクトプロパティの取得以上の操作が必要な場合、コードベース全体のアクセサを検索して変更する必要がなくなります。
  • set処理時にバリデーションを追加するのが容易になります。
  • 内部表現をカプセル化します。
  • 値の取得・設定時のロギングやエラーハンドリングを簡単に追加可能です。
  • サーバーから取得するなど、オブジェクトプロパティの遅延読み込みを実装可能です。

悪い例:

javascript
function makeBankAccount() {
  // ...

  return {
    balance: 0
    // ...
  };
}

const account = makeBankAccount();
account.balance = 100;

良い例:

javascript
function makeBankAccount() {
  // this one is private
  let balance = 0;

  // a "getter", made public via the returned object below
  function getBalance() {
    return balance;
  }

  // a "setter", made public via the returned object below
  function setBalance(amount) {
    // ... validate before updating the balance
    balance = amount;
  }

  return {
    // ...
    getBalance,
    setBalance
  };
}

const account = makeBankAccount();
account.setBalance(100);

オブジェクトにプライベートメンバーを持たせる

クロージャーを利用して実現可能(ES5以下の場合)

悪い例:

javascript
const Employee = function(name) {
  this.name = name;
};

Employee.prototype.getName = function getName() {
  return this.name;
};

const employee = new Employee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined

良い例:

javascript
function makeEmployee(name) {
  return {
    getName() {
      return name;
    }
  };
}

const employee = makeEmployee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe