[ Javascript ] クラスの継承とオーバーライド ( prototype )

Pocket

JavaScript においてオブジェクト指向言語の継承のような実装方法はいくつか存在すると思いますが、ここでは prototype を使ったサンプルスクリプトを掲載しています。他言語の継承と比較しますと記述方法に違和感を覚えるかもしれませんが、コメントを参照いただければ理解できると思います。

スポンサーリンク

オブジェクト指向 継承のサンプルスクリプト

// 季節クラス(親クラス)
var Season = function () { }

// プロトタイプ(メンバ変数)
Season.prototype.temperature = 15; // 気温
Season.prototype.humidity    = 50; // 湿度

// プロトタイプの追加(足し算メソッド)
Season.prototype.year_description = function () {
    return '年間平均気温15度 平均湿度50%';
}

// 春クラス(子クラス)
var Spring = function () { }

// 春クラスのプロトタイプに、季節クラスのプロトタイプを設定
Spring.prototype = new Season();
// 春クラス独自ののプロトタイプを設定
Spring.prototype.spring_description = function () {
    return '春の平均気温10度 平均湿度40%';
}


// インスタンスを生成する
var spring = new Spring();

alert(spring.spring_description());
alert(spring.year_description());

alert(spring.temperature); // 15

spring.temperature = 10;  // 春の気温を設定
spring.humidity    = 40;  // 春の湿度を設定

alert(spring.temperature); // 10

なお、Season クラスの場合であれば、プロトタイプは以下のように一括で記述することもできます。こちらのほうがわかりやすいかもしれません。

var Season = function () { }
Season.prototype =
{
    temperature          : 15,
    humidity             : 50,
    year_description  : function() { return '年間平均気温15度 平均湿度50%'; }
};

継承したメソッドをオーバーライドする

次に継承したクラスメソッドをオーバーライドします。オーバーライドも prototype を使用して実現しています。詳細はコメントを参照ください。

// 季節クラス(親クラス)
var Season = function () { }
Season.prototype =
{
    temperature          : 15,
    humidity             : 50,
    description  : function() { return '年間平均気温15度 平均湿度50%'; }
};

// 春クラス(子クラス)
var Spring = function () { }

// 春クラスのプロトタイプに、季節クラスのプロトタイプを設定
Spring.prototype = new Season();

// 季節(親)クラスのメソッドをオーバーライド
Spring.prototype.description = function () {
    return '春の平均気温10度 平均湿度40%';
}

// インスタンスを生成する
var spring = new Spring();

alert(spring.description()); // '春の平均気温10度 平均湿度40%'
スポンサーリンク


Pocket

One thought on “[ Javascript ] クラスの継承とオーバーライド ( prototype )”

  1. Pingback: Javascript でオブジェクト指向 オーバーライドとオーバーロード – 偏差値40の高い壁

Leave a Comment

Your email address will not be published. Required fields are marked *