LoginSignup
0
1

More than 5 years have passed since last update.

オブジェクト指向初心者向け、クラスとインスタンスの説明

Last updated at Posted at 2017-11-28
// オブジェクト指向用語説明用サンプル
//
// class(クラス) :
//   データと関数 をひとまとめにした入れ物の定義(型)。
//   一般に、クラスが持つデータのことを「フィールド」、
//   クラスが持つ関数のことを「メソッド」と呼ぶ。
//   メソッドは引数で値を与えられなくても、自身のフィールドを
//   使うことができる。
//
// instance(インスタンス) :
//   クラスを実体化したもの。
//   クラスは型であり、その型を元にインスタンスを何個でも
//   生成できる。
//   オブジェクト指向プログラミングでは、インスタンスを生成して、
//   それに対して操作を行うことで処理を行う。
//
// this :
//   メソッドの中で、this という変数を使うことができる。
//   this は自身のインスタンスへの参照。 this を通して、自身の
//   メソッドやフィールドにアクセスできる。

// 商品クラス定義
class Product {
  // フィールド
  name: string;
  price: number;

  // コンストラクタ(newされたときに呼ばれるメソッド)
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

// 注文クラス定義
class Order {
  // フィールド (Product(商品)型のインスタンスの配列を持つ)
  products: Product[];

  // コンストラクタ(newされたときに呼ばれるメソッド)
  constructor(products: Product[]) {
    this.products = products;
  }

  // メソッド
  totalPrice() {
    // ↓ 商品の配列から、各商品の値段(price)の配列に変換する。
    const prices = this.products.map((product) => {return product.price;});
    // ↓ 値段の合計を計算して返す。
    return this.sum(prices);
  }

  sum(prices: number[]) {
    return prices.reduce((prev, cur) => {return prev + cur;}, 0);
  }

  productNamesStr() {
    // ↓ 商品の配列から、各商品の名前(name)の配列に変換する。
    const names = this.products.map((product) => {return product.name;});
    // ↓ 商品名をコンマで連結して返す。
    return names.join(', ');
  }
}

function main() {
  // Product(商品) のインスタンスを生成し、配列に格納する。
  const products = [
    new Product('広辞苑', 4500),
    new Product('大辞林', 5000),
    new Product('吾輩は猫である', 700)
  ];

  // Order(注文) のインスタンスを生成
  const order = new Order(products);

  // Order(注文) のメソッドを使って処理する
  console.log(`total price: ${order.totalPrice()}`); // 注文に、合計金額を計算させる。
  console.log(`product names: ${order.productNamesStr()}`); // 注文が含む商品の名前を取得する。
}

main(); // ← ここからプログラムの実行が開始される。
// => total price: 10200
// => product names: 広辞苑, 大辞林, 吾輩は猫である
0
1
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
1