Here is the code:

var Circle = function( radius )
{
    var _radius = radius,
    _area = function()
    {
        return Math.PI * _radius * _radius;
    },
    _perimeter = function()
    {
        return 2 * Math.PI * _radius;
    };

    this.radius = _radius;
    this.area = "Area" + _area();
    this.perimeter = "Perimeter" + _perimeter();
    this.setRadius = function( radius ) {
        _radius = radius;
    };
};

However I cannot get the this.setRadius() function to successfully mutate the private properties. For instance, I run this:

var circle = new Circle(5);
alert(circle.area);
circle.setRadius(10);
alert(circle.radius);

And it outputs 78.blah which is correct, then it outputs a radius of 5.

Any suggestions would be greatly appreciated! I thought that since the _area property is a function, it would recalculate each time, but I guess it's not? but why is this.radius not returning the new radius when it is obviously being reset?

Thanks!

Thanks guys, I decided to do it the following way:

var Circle = function( radius )
{
    var _radius = radius;

    this.radius = function()
    {
        return _radius;
    };
    this.area = function()
    {
        return Math.PI * _radius * _radius;
    }
    this.perimeter = function()
    {
        return 2 * Math.PI * _radius;
    }
    this.setRadius = function( radius ) {
        _radius = radius;
    };
};

It works now, so all's good!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.