継承

JavaScriptは、クラスの継承をする方法が複数あるらしい。
以下のやつが簡単そうなので採用。

  • 継承の方法
// 親クラスのコンストラクタ
function 親クラス名() {
  ....
}

// 親クラスのメソッド
親クラス名.prototype.メソッド名 = function() {
  ....
}

// 子クラスのコンストラクタ
function 子クラス名() {
  親クラス名.call(this); // 親クラスのコンストラクタを明示的に呼ぶ
  ....
}

// 子クラスのメソッド
子クラス名.prototype = new 親クラス名(); // 親クラスのメソッドを明示的に引きつぐ

子クラス名.prototype.メソッド名 = function() {
  ....
}
  • サンプル

親クラスUnit、子クラスEnemy,Cannon

<html>
<head runat="server">
<title></title>
<script src="../lib/jquery-1.4.min.js" type="text/javascript"></script>
</head>
<body onload="sampleMain()">
<script language="JavaScript">

// Unitクラス
function Unit(number) {
  this.number = number;
}

Unit.prototype.getNumber = function() {
  return this.number;
}

Unit.prototype.getName = function() {
  return "";
}

Unit.prototype.getDescription = function() {
  return this.getName() +  this.number;
}

// Enemyクラス(extends Unit)
function Enemy(number) {
  Unit.call(this, number);
}

Enemy.prototype = new Unit();
Enemy.prototype.getName = function() {
  return "敵船";
}

// Cannonクラス(extends Unit)
function Cannon(number) {
  Unit.call(this, number);
}

Cannon.prototype = new Unit();
Cannon.prototype.getName = function() {
  return "砲台";
}

function sampleMain() {
  var u1 = new Enemy(1);
  var u2 = new Cannon(2);

  $("#text1").html(
     u1.getDescription() +  // "敵船1"
     u2.getDescription()    // "砲台2"
  );
}

</script>
<p id="text1"></p>
</body>
</html>