Challenge: Solution Review
This lesson will explain the solution to the problem from the last coding challenge.
We'll cover the following
Solution #
class Human{constructor(name, age, occupation){this.name = name;this.age = age;this.occupation = occupation;}}var person = new Human("Elle","23","Engineer")console.log(person)
Explanation #
The ES6 version of JavaScript uses classes defined using the class
keyword to implement the constructor pattern. In this case, the constructor
is present as a separate function inside the class. Let’s discuss the solution in detail.
Originally, you were given the following code:
function Human(name, age, occupation){this.name = name;this.age = age;this.occupation = occupation;}var person = new Human("Elle","23","Engineer")console.log(person)
To convert it to the ES6 version:
-
Replace the keyword
function
with classclass Human
-
Inside the class, define the constructor using the
constructor
keyword. Passname
,age
, andoccupation
as parameters to this constructor.constructor(name,age,occupation)
Note that in ES5 version the parameters were passed to the constructor function.
function Human(name,age,occupation) //ES5
-
Initialize all the properties inside the
constructor
.this.name = name; this.age = age; this.occupation = occupation;
-
The object
person
is created using thenew
keyword just as in the ES5 version.
Just as with the ES5 version, multiple objects can be created from the same class.
Let’s discuss the singleton pattern in the next lesson.