taquaki-satwo
12/9/2017 - 2:30 AM

## コンストラクタ継承

JS-コンストラクタ継承

``````// スーパークラス
function Ellipse(a, b) {
this.a = a;
this.b = b;
}

Ellipse.prototype.getArea = function() {
return Math.PI * this.a * this.b;
};

Ellipse.prototype.toString = function() {
return `Ellipse \${this.a} \${this.b}`;
}

var ellipse = new Ellipse(5, 3);

console.log(ellipse.getArea());
console.log(ellipse.toString());

// サブクラス
function Circle(r) {
this.a = r;
this.b = r;
}
Circle.prototype = Object.create(Ellipse.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: Circle,
writable: true
}
})
Circle.prototype.toString = function() {
return `Circle \${this.a} \${this.b}`;
}

var circle = new Circle(2);

console.log(circle);
console.log(circle.getArea());
console.log(circle.toString());

// サブクラスその２
function Circle2(r) {
Ellipse.call(this, r, r);
}
Circle2.prototype = Object.create(Ellipse.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: Circle,
writable: true
}
});
Circle2.prototype.toString = function() {
return `Circle \${this.a} \${this.b}`;
}

var circle2 = new Circle2(3);
console.log(circle2.getArea());
console.log(circle2.toString());

// サブクラスその3
// 擬古典的継承
function Circle3(r) {
Ellipse.call(this, r, r);
}
Circle3.prototype = Object.create(Ellipse.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: Circle,
writable: true
}
});
Circle3.prototype.toString = function() {
var str = Ellipse.prototype.toString.call(this);
return str.replace('Elipse', 'Circle');
}

var circle3 = new Circle3(10);
console.log(circle3.getArea());
console.log(circle3.toString());``````

## JS-コンストラクタ継承

A Pen by Takaaki Sato on CodePen.

``#cnt``