簡單的javascript程序來顯示單擊按鈕時哪個矩形具有較大的周長,但Rectangle.Perimeter似乎沒有從矩形對象的寬度和高度獲得所需的值。它只是打印NaN而不是周界。javascript原型方法
<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>
當您創建'Rectangle.prototype.RectanglePerimeter',這是什麼'this'指什麼? – Blender
我想你的意思是讓'RectanglePerimeter'成爲一個函數。 – 4castle
事情是,當我打電話給Rectangle1.RectanglePerimeter時,我希望它引用Rectangle1的寬度和高度,從這裏調用 var Rectangle1 = new Rectangle(2,4); 顯然我不知道該怎麼做:)) –