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.
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.
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
nameand assigns it to variable_namedeclared usingvarkeyword. Variable_nameremains private asthisis not used (line 5). - Has property
getNamedefined usingthiskeyword. It is assigned