OOJS 1 - Practice

OOJS 1 solution1:

function Shape(name, sides, sideLength) {
this.name = name;
this.sides = sides;
this.sideLength = sideLength;
this.calcPerimeter = function() {
return (Result of ${this.name} is : ${this.sides*this.sideLength});
};
}

// create object
let square = new Shape(“square”, 4, 5);
console.log(square.calcPerimeter());

let triangle = new Shape(“triangle”, 3, 3);
console.log(triangle.calcPerimeter());

OOJS 1 solution2:

function Shape(name, sides, sideLength) {
    this.name = name;
    this.sides = sides;
    this.sideLength = sideLength;
    this.calcPerimeter = function() {
        if (this.name === "square") {
            console.log(sideLength * sides);
        } else if (this.name === "triangle") {
            console.log(sideLength * sides);
        }
    };
}

// create object
let square = new Shape(“square”, 4, 5);
console.log(square.calcPerimeter());

let triangle = new Shape(“triangle”, 3, 3);
console.log(triangle.calcPerimeter());

@ranjanrnj44 This looks good as well.

1 Like

I thought the calculation for perimeter is

Perimeter = (L+W)*2

Since the exercise is about shapes of equal length, sideLength * sides is fine. (The constructor has only one parameter for side length.)
You’re formula would be needed if we’re talking about rectangles where the width and the height are different.
The most general form would be arbitrary shapes where we have a different length (and therefore parameter) for every side.

1 Like