javascript原型方法

时间:2016-10-23 15:50:45

标签: javascript prototype

简单的javascript程序,用于在单击按钮时显示哪个矩形具有更大的周长,但 Rectangle.Perimeter 似乎无法从 Rectangle 对象获取所需的值宽度和高度。它只是打印NaN而不是周边。

<script>
    function Rectangle(width, height) {
        this.width = width;
        this.height = height;
    }
    var Rectangle1 = new Rectangle(2, 4);
    var Rectangle2 = new Rectangle(8.5, 11);

     Rectangle.prototype.PrintRectangle = function () {
        document.getElementById("p1").innerHTML = "Rectangle width is " + this.width + " and Rectangle height is "+ this.height;
    };
    Rectangle.prototype.RectanglePerimeter = this.width*2 + this.height*2;


    function calculate() {
        if(Rectangle1.RectanglePerimeter > Rectangle2.RectanglePerimeter){
            document.getElementById("perimetar").innerHTML = "The biggest Rectangle has perimeter of " + Rectangle1.RectanglePerimeter;
        }else{
            document.getElementById("perimetar").innerHTML = "The biggest Rectangle has perimeter of " + Rectangle2.RectanglePerimeter;
        }
    }

</script>

<body>
<p><b>Paragraph no: 1</b></p>
<p id="p1" onload="Rectangle1.PrintRectangle()"></p>
<button id="button" onclick="calculate()">Calculate Perimeter</button>
<p id="perimetar"></p>
</body>

1 个答案:

答案 0 :(得分:0)

Rectangle.prototype.getPerimeter = function() { 
    return this.width*2 + this.height*2;
};

然后使用

if(Rectangle1.getPerimeter() > Rectangle2.getPerimeter())