JavaScript Inheritance

Copyright Information: © 1998-2005 by individual mozilla.org contributors; content available under a Creative Commons license (CC BY-SA 2.0)

by FiNGAHOLiC

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

JavaScript

// Person クラスの定義
function Person() {}

Person.prototype.walk = function() {
    console.log('I am walking!');
};
Person.prototype.sayHello = function() {
    console.log('hello');
};

// Student クラスの定義
function Student() {
    // 親クラスのコンストラクタを呼び出す
    Person.call(this);
}

// Person のメソッドを継承する
Student.prototype = new Person();

// Person を指しているコンストラクタのポインタを修正する
Student.prototype.constructor = Student;

// sayHello メソッドをオーバーライドする
Student.prototype.sayHello = function() {
    console.log('hi, I am a student');
};

// sayGoodBye メソッドを追加する
Student.prototype.sayGoodBye = function() {
    console.log('goodBye');
};

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// 継承のチェック
console.log(student1 instanceof Person); // true 
console.log(student1 instanceof Student); // true