0

I have following Html file with javascript. This gives me error that "testCircle is undefined." kinldy help me resolve this.

<html>
    <body>
    <h1> Testing Object-based Javascipt </h1>
    <script type="text/javascript">
    function mycircle(x,y,r)
    {
    this.xcoord=x;
    this.ycoord=y;
    this.radius=r;
    this.area = getArea;
    this.getCircumference = function () { return (2 * Math.PI * this.radius ) ; };
    }
   function getArea()
   {
   return (Math.PI * this.radius * this.radius);
   }
        var testCircle = mycircle(3,4,5);

   window.alert('The radius of my circle is ' + testCircle.radius);

   </script>

   </body>
   </html>

Thanks in advance....

1
  • 2
    ..and what does mycircle() return? Exactly - nothing (undefined) Commented May 20, 2012 at 17:16

2 Answers 2

5
var testCircle = mycircle(3, 4, 5);

should be

var testCircle = new mycircle(3, 4, 5);

Constructors are to be called with the new keyword. If the keyword is not used, you're assigning the return value of the mycircle function. And as mycircle contains no return statement, the return values is undefined - that's what you assigned to testCircle in your code.

Sign up to request clarification or add additional context in comments.

Comments

0

The error I'm getting is radius of undefined. If this is the case. You need to return this at the end of mycircle if you planned to use it without new constructor.

As seen on updated: this fiddle here.

Fix: Broken link

2 Comments

This is a wrong way of creating an object. In your code, mycircle is called in the global context, so this refers to window. You're appending the xcoord, ycoord, ... etc. properties to the window object and returning a reference to it. The whole circle is thus kept as a set of properties of window and another call to mycircle will overwrite it.
forgive me for the incomplete fiddle. assuming the object does created in the local scope. as I've just copy the code and paste them to test. it was meant to return mycircle. but you are right.

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.