0

我有以下带有 javascript 的 Html 文件。这给了我“testCircle 未定义”的错误。kinldy 帮我解决这个问题。

<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>

提前致谢....

4

2 回答 2

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

应该

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

构造函数将使用new关键字调用。如果未使用关键字,则您正在分配mycircle函数的返回值。由于mycircle不包含任何return语句,因此返回值是undefined- 这就是您testCircle在代码中分配的值。

于 2012-05-20T17:18:12.157 回答
0

我得到的错误是未定义的半径。如果是这种情况。如果您打算在没有新构造函数的情况下使用它,则需要在 mycircle 末尾返回它。

更新所见:this fiddle here

修复:断开的链接

于 2012-05-20T17:27:32.487 回答