Core > 継承

by s_hiroshi

JavaScript

/*
 * thisプロパティのapply関数で行いプロトタイプの継承はfor in文行う。
 * 親 : ParentObject
 * 子 : ChildObject
 */

var ParentObject = function(value) {
    this.name = value;
};
ParentObject.prototype.family = '山田';
ParentObject.prototype.showFullName = function() {
    return this.family + ' ' + this.name;
};

var ChildObject = function(name, gender) {
    // thisプロパティを継承
    ParentObject.apply(this, [name]);
    // ChildObject固有のプロパティ
    this.gender = gender;
};
// prototypeプロパティを継承
for (var prop in ParentObject.prototype) {
    ChildObject.prototype[prop] = ParentObject.prototype[prop];
};
// 継承先のインスタンスを作成
var child = new ChildObject('小太郎', '男');
// 実行画面 アラートボックス
alert(child.showFullName() + ' : ' + child.gender);
// 山田 小太郎 : 男