DEV Community

Salah Eddine Ait Balkacm
Salah Eddine Ait Balkacm

Posted on

1 1

Inheritance In ES6

Inheritance In ES6

Classes In ES6

Implementing a Class

  • to Implement a class we use the class keyword.
  • every class must have a constructor function. attributes of that class are defined using getters/setters(functions as well).
  • as for attributes we use getters and setters.
  • getter and setter are special kind of methods that allow us to set the value of an attribut, and get the values of an attribute.
class Person {
  //getter
  //here we used the get keyword and then the name of the getter
  get Name() {
    return this.name; //here we simply return the value of that attribute but with the this key word
    //so that we get the attribute of the select instance of that class
  }
  //setter
  set Name(name_) {
    //and here we set the value of the attribute
    this.name = name_;
  }
  //getter
  get Age() {
    return this.age;
  }
  //setter
  set Age(age_) {
    this.age = age_;
  }
  //constructor
  constructor(name_, age_) {
    this.name = name_;
    this.age = age_;
    this.canWalk = function() {
      console.log("YAY !! I'm Walking");
    };
  }
}
//this is an instance of a Person
let me = new Person("salah", 25);
console.log(me); //Person {name:'salah',age:25}

console.log(me.Age); //getter
me.Age = 22; //setter
console.log(me.Name); //getter
me.Name = "SALAH EDDINE"; //setter

console.log(me); //Person {name:'SALAH EDDINE',age:22}

Inheritance

  • In modern javascript we have the extends key work which makes easier to implement
  • inheritance in between our classes.
  • Male extends Person means that Male class has all the properties and methods of Person And also have it's own.
class Male extends Person {
  //getter
  get Gender() {
    return this.gender;
  }
  constructor(name_, age_ /*,here we can add other attributes as well*/) {
    //in the child class(Male) we must call the parent constructor first
    //we do that using the super method and pass to it age_ and name_ parent properties
    super(name_, age_);
    //and now we assign the child property gender which in this case will have a fixed value
    this.gender = "male";
  }
}
//this is an instance of a male
let MalePerson = new Male("mohammed", 15);
console.log(MalePerson); //Male{name:'mohammed',age:15,gender:''male}

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay