Core > 継承
「やっと理解できた!JSオブジェクト指向プログラミング再入門 」を参考にした継承
by s_hiroshi
JavaScript
// Person クラスの定義
function Person() {
// インスタンスメソッドは継承される
this.jogg = function() {
console.log('I am jogging!');
}
}
// プロトタイプメソッド
Person.prototype.walk = function() {
console.log('I am walking!');
};
// プロトタイプメソッド
Person.prototype.run = function() {
console.log('I am running!');
}
// クラスメンバは継承されない
Person.WALKSPEED = 4;
// Student クラスの定義
function Student() {
// 親クラスのコンストラクタを呼び出す
// 本サンプルでは無くても動作は変わらない
Person.call(this);
}
// Person のメソッドを継承する
// インスタンスをprototypeに設定する(インスタンスベース)
// インスタンスメンバ、プロトタイプメンバを継承する
// 静的メンバは継承しない
Student.prototype = new Person();
// Person を指しているコンストラクタのポインタを修正する
// prototyp.constructorはコンストラクタとして利用される場合に備える
Student.prototype.constructor = Student;
// run メソッドをオーバーライドする
Student.prototype.run = function() {
console.log('I am running fast!');
};
var student1 = new Student();
student1.walk();
student1.jogg();
student1.run();
console.log(Student.WALKSPEED) //undefined
console.log(Student.prototype.WALKSPEED); // undefined
// 継承のチェック
console.log(student1 instanceof Person); // true
console.log(student1 instanceof Student); // true