質問

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!

EDIT:

Alright, thanks for why the radius isn't working correctly. That is a little obvious. As pointed out, I do not ever update this.radius. However, the point remains that the _area and _perimeter values are not updated either.

I run:

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

And I still get the old area even after updating the radius. Note that the _area function is dependent on _radius and not this.radius.

役に立ちましたか?

解決

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. Thanks for the tips!

他のヒント

the simple answer is because you're not setting the radius property in the setRadius function.

You set the private property _radius but there is nothing in your function that updates the this.radius.

EDIT: I updated my answer to how i would have solved this problem. Could be better I guess but just a simple way of doing it.

var Circle = function( radius )
{
    var radius, area, perimeter;

    this.setRadius = 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(radius);
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top