我为练习问题制作了两个'square'和'rect'对象。但现在我想尝试将它们显示为实际形状。我可以用物体做这个吗?如果是这样的话?或者我将别无选择,只能使用rect();方法
这是我的代码片段,显示了对象属性。 更新:添加其余代码以便更好地理解。
// Determines the 'shapeType' depending on the perimeters.
var shapeType = function (shape) {
if ( shape.height === shape.width ) {
shape.shapeType = "square";
} else if ( shape.height != shape.width ) {
shape.shapeType = "rectangle";
}
};
// Used to change height and width of the quad.
var quadSize = function (newHeight, newWidth) {
this.height = newHeight;
this.width = newWidth;
};
// Checks both objects 'rect' / 'square' to determine the perimeter's are proper.
var shapeWrapper = function (shape) {
if ( shape === square ) {
if ( shape.height != shape.width ) {
console.log("ERROR: Object 'square' is outputed as a rectangle.");
}
} else if ( shape === rect ) {
if ( shape.height === shape.width ) {
console.log("ERROR: Object 'rect' is outputed as a square.");
}
}
};
var square = {
objName: "square"
};
square.quadSize = quadSize;
square.quadSize(42, 42);
square.shapeType = shapeType;
square.shapeType(square);
var rect = {
objName: "rect"
};
rect.quadSize = quadSize;
rect.quadSize(42, 24);
rect.shapeType = shapeType;
rect.shapeType(rect);
// Outputs objects 'rect' and 'square'
console.log(square);
console.log(rect);
// Outputs an ERROR if the shapes perimeters are improper.
shapeWrapper(square);
shapeWrapper(rect);
谢谢!