Javascript显示功能文本而不是在屏幕上打印值

时间:2009-12-05 20:42:54

标签: javascript

function hex(x,y,side,isLast,color)
{//Hex object constructor.

    this.x = x;
    this.y = y;
    this.side = side;
    this.isLast = isLast;
    this.color = color;

    function multiply()
    {
        return this.x * this.y;
    }

    this.multiply = multiply;
}


var hexagon = new hex(22,22,20,0,1);

document.write(hexagon.multiply);

当加载index.htm时,结果在屏幕上写入函数而不是返回值:

function multiply(){return this.x * this.y; }

:(

2 个答案:

答案 0 :(得分:6)

你忘了():

document.write(hexagon.multiply());

如果您不使用(),Javascript会将multiply视为变量并将其写出来 - 在本例中为函数的代码。

答案 1 :(得分:2)

您必须确保您的javascript代码位于<script></script>标记中。所以,它可能是:

<html><head><script type="text/javascript">
function hex(x,y,side,isLast,color)
{//Hex object constructor.

    this.x = x;
    this.y = y;
    this.side = side;
    this.isLast = isLast;
    this.color = color;

    function multiply()
    {
        return this.x * this.y;
    }

    this.multiply = multiply;
}


var hexagon = new hex(22,22,20,0,1);

document.write(hexagon.multiply)
</script>
<body>
<!--Content here-->
</body>
</html>