tddjs > p149

継承のダメな例 CircleオブジェクトのインスタンcにもSphereのhelloが追加される。

by s_hiroshi

JavaScript

function Circle(radius) {
    if (!(this instanceof Circle)) {
        return new Circle(radius);
    }

    this.radius = radius;
}

(function(p) {
    function diameter() {
        return this.radius * 2;
    }

    function circumference() {
        return this.diameter() * Math.PI;
    }

    function area() {
        return this.radius * this.radius * Math.PI;
    }

    p.diameter = diameter;
    p.circumference = circumference;
    p.area = area;
}(Circle.prototype));

var c = new Circle(2);
function Sphere(radius) {
    this.radius = radius;
}


// Sphere.prototype = new Circle() これは引数を取れないのでダメ
Sphere.prototype = Circle.prototype;
Sphere.prototype.hello = function() {
    return 'hello';
}
Sphere.prototype.constructor = Sphere;
var s = new Sphere(8);
console.log(c.hello())
console.log(s.diameter());
console.log(s instanceof Sphere);
console.log(c instanceof Sphere);