DEV Community

Ryan Ameri
Ryan Ameri

Posted on

Mastering Hard Parts of JavaScript: Prototype & Class IV

Using ES6 Classes

Exercise 8

Create a class PersonClass. PersonClass should have a constructor that is passed an input of name and saves it to a property by the same name. PersonClass should also have a method called greet that logs the string 'hello'.

class PersonClass {
  constructor() {
    // add code here
  }

  // add code here
}
const george = new PersonClass();
george.greet();
// -> Logs 'hello'

Solution 8

class PersonClass {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log("hello");
  }
}

An exact recreation of Exercise 2 and 5, here using the class pattern. More readable for people who come from other languages, though many JS diehards complain that this pattern just doesn't look native to JS. In effect the JS engine is doing exactly what it did in Exercise 5.

Exercise 9

Create a class DeveloperClass that creates objects by extending the PersonClass class. In addition to having a name property and greet method, DeveloperClass should have an introduce method. When called, introduce should log the string 'Hello World, my name is [name]'.

const thai = new DeveloperClass("Thai", 32);
console.log(thai.name);
// -> Logs 'Thai'
thai.introduce();
//-> Logs 'Hello World, my name is Thai'

Solution 9

class DeveloperClass {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  introduce() {
    console.log(`Hello World, my name is ${this.name}`);
  }
}

This of course is exactly like exercise 7, but uses the class syntax instead of adding a method to the prototype property directly. Again, behind the scenes, the JS engine performs exactly the same operation.

Discussion (1)

Collapse
zhej profile image
Zhej

Exercise 9 is asking to use the extends keyword on the parent object to inherit properties, not create an entire new class.

I wanted to know why you don't have to use the super inside the class though.

class DeveloperClass extends PersonClass {
// super(name) {
// this.name = name;
// }
introduce() {
console.log('Hello World, my name is ' + this.name);
}
}

still managed to get the right answer