Solution Review: Modeling Classes
Solution review to exercise for OOPs using classes and constructor functions.
We'll cover the following...
Solution
The problem can be solved using either the classes or constructor functions. The two approaches only differ syntactically. Let’s look at the two approaches individually.
Constructor function approach
Within this approach, create a constructor function for the two classes and link them together by setting prototype values for inheritance. Examine the following code.
Press + to interact
// Create Constructor function for Shapefunction Shape(name){// Define private variable by using 'var' keyword// The variable _name will not be accessible outsidevar _name= name; // assign argument to variable _name// Create property getName using `this` and assign it to function// to return private variable _namethis.getName = ()=>{return _name;}}// Create Constructor Function for Rectangle which is derived from Shapefunction Rectangle (name, side1, side2){// Define properties for parent Constructor functionShape.call(this, name);// Define public properties for Rectangle Constructor Functionthis.side1 = side1;this.side2 = side2;// Define method getAreathis.getArea = ()=>{return this.side1 * this.side2;}// Define method isSquarethis.isSquare = ()=>{return this.side1 === this.side2;}}// Inherit prototype propertyRectangle.prototype = Object.create(Shape.prototype);Rectangle.prototype.constructor = Rectangle;var obj = new Rectangle('Rectangle', 3, 4); // create Rectangle objectconsole.log(obj.name, obj.side1, obj.side2);console.log("obj getName method:",obj.getName());console.log("obj isSquare method:",obj.isSquare());console.log("obj getArea method:",obj.getArea());
In the code, we create two constructor functions: Shape
(lines 2 to 11) and Rectangle
(lines 14 to 29). Let’s look at each one.
Shape
constructor function:
- Takes one argument