tddjs > p160 オブジェクトの拡張

by s_hiroshi

JavaScript

/*jslint indent: 2*/

function circle(radius) {
    function getSetRadius() {
        if (arguments.length > 0) {
            if (arguments[0] < 0) {
                throw new TypeError("Radius should be >= 0");
            }

            radius = arguments[0];
        }

        return radius;
    }

    function diameter() {
        return radius * 2;
    }

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

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

    return {
        radius: getSetRadius,
        diameter: diameter,
        area: area,
        circumference: circumference
    };
}

/*jslint indent: 2, onevar: false*/
/*globals circle*/


function sphere(radius) {
    var sphereObj = circle(radius);
    var circleArea = sphereObj.area;

    function area() {
        console.log(circleArea.call(this));
        return 4 * circleArea.call(this);
    }
    sphereObj.area = area;
    return sphereObj;
}

var s = sphere(10);
console.log(s.area());
console.log(s instanceof sphere); // false new演算子を使っていないのでinstanceofはfalse