0

I'm learning OO JavaScript (again). I've written this simple object

function circle(){
  this.radius = 4;
}

circle.prototype.area = function(){
  this.radius * this.radius * 3.14;
};

var c = new circle();
c.area();

The value returned by c.area() is undefined. I guess this can only because this.radius is not returning 4, why not?

2
  • 2
    Use Math.PI instead of 3.14. Commented Sep 28, 2011 at 8:51
  • 1
    By convention, constructors start with a capital letter. By default they return the newly constructed object so you don't need a return statement. But methods must have a return statement if you want them to return a value. Commented Sep 28, 2011 at 9:15

1 Answer 1

6

radius has the value of 4, but the area method doesn't return any value.

circle.prototype.area = function(){
  return this.radius * this.radius * 3.14;
};
Sign up to request clarification or add additional context in comments.

4 Comments

I would add: if (typeof this.area != 'number') this.area = Math.pow(this.radius, 2)*Math.PI; return this.area;.
@RobG I wouldn't. In fact, you'd override the area() method with the area member => area will be callable at the beginning but won't after the first call.
@duri thanks, I've been using Groovy for too long (where the return statement is optional)
@duri - doh, of course! Anyhow, just an exercise for the OP I suspect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.