LoginSignup
13
12

More than 5 years have passed since last update.

プロトタイプオブジェクトを理解する

Posted at

概要

オライリー シングルWebアプリケーションでJavaScriptオブジェクト、
プロトタイプに関してのデザインパターンのメモ。

クラスベースの例え

建築士は家の設計図を作成し、その設計図に基づいて
家を建築する

プロトタイプベースの例え

建築士は家を建築してから、その家のような家を建築する

プロトタイプベース

proto.js
// 骨組み
var proto = {
  sentence : 4,
  probation : 2
};

// ここでプロトタイプをつくる
var Prisoner = function(name, id) {
  this.name = name;
  this.id = id;
};
// 宣言
Prisoner.prototype = proto;

// ---

// 上記をもとに生成されていく
var firstPrisoner = new Prisoner('joe', '12A');
var secondPrisoner = new Prisoner('maroru', '2B');

Object.createを使う

object.js
var proto = {
  sentence : 4,
  probation : 2
};

var firstPrisoner = Object.create(proto);
firstPrisoner.name = 'joe';
firstPrisoner.id = '12A';

var secondPrisoner = Object.create(proto);
secondPrisoner.name = 'same';
secondPrisoner.id = '2BC';

ファクトリ関数を使う

object02.js
var proto = {
  sentence: 4,
  probation: 2
};

// ファクトリ関数にはmake<Object_name>と名付ける
var makePrisoner = function(name, id) {
  var prisoner = Object.create(proto);
  prisoner.name = name;
  prisoner.id = id;
  return prisoner;
};

var firstPrisoner = makePrisoner('joe', '12A');
var secondPrisoner = makePrisoner('sam', '2BC');


まとめ

基本的にはファクトリ関数を使うことがベストプラクティスらしいです。

13
12
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
13
12