Search⌘ K

Solution Review: Modeling Classes

Explore JavaScript object-oriented programming by examining solutions that model classes using both constructor functions and ES6 classes. Understand how inheritance works through prototypes and extends keyword, and learn how to implement key methods for shapes like rectangles. This lesson deepens your knowledge of OOP concepts and practical syntax in JavaScript.

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.

Node.js
// Create Constructor function for Shape
function Shape(name){
// Define private variable by using 'var' keyword
// The variable _name will not be accessible outside
var _name= name; // assign argument to variable _name
// Create property getName using `this` and assign it to function
// to return private variable _name
this.getName = ()=>{
return _name;
}
}
// Create Constructor Function for Rectangle which is derived from Shape
function Rectangle (name, side1, side2){
// Define properties for parent Constructor function
Shape.call(this, name);
// Define public properties for Rectangle Constructor Function
this.side1 = side1;
this.side2 = side2;
// Define method getArea
this.getArea = ()=>{
return this.side1 * this.side2;
}
// Define method isSquare
this.isSquare = ()=>{
return this.side1 === this.side2;
}
}
// Inherit prototype property
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var obj = new Rectangle('Rectangle', 3, 4); // create Rectangle object
console.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 name and assigns it to variable _name declared using var keyword. Variable _name remains private as this is not used (line 5).
  • Has property getName defined using this keyword. It is assigned
...