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....
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....
Share Improve this question asked May 20, 2012 at 17:15 nanosoftnanosoft 3,0996 gold badges44 silver badges66 bronze badges 1-
2
..and what does
mycircle()
return? Exactly - nothing (undefined
) – Mārtiņš Briedis Commented May 20, 2012 at 17:16
2 Answers
Reset to default 5var 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.
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