【问题标题】:Javascript showing the function text instead of printing value on screenJavascript 显示函数文本而不是在屏幕上打印值
【发布时间】:2010-12-23 15:05:27
【问题描述】:
函数 hex(x,y,side,isLast,color) {//十六进制对象构造函数。 这个.x = x; 这个.y = y; this.side = 边; this.isLast = isLast; this.color = 颜色; 函数乘法() { 返回 this.x * this.y; } this.multiply = 相乘; } var hexagon = new hex(22,22,20,0,1); document.write(hexagon.multiply);

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

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

:(

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您必须确保您的 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>
    

    【讨论】:

    • 好主意,但不是我认为的重点 - 如果是的话,它将显示整个函数,而不仅仅是 multiply()。
    【解决方案2】:

    你忘记了 ():

    document.write(hexagon.multiply());
    

    如果不使用 (),Javascript 会将multiply 视为变量并写出它的内容——在这种情况下,是函数的代码。

    【讨论】:

    • 德纳达! (根据姓氏猜测语言环境 - 如果我错了,请原谅我;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    相关资源
    最近更新 更多