Curriculum
Course: React
Login

Curriculum

React

Text lesson

Method in Classes

You can include your own methods within a class:

Example

Define a method called “present”:

class Car {
 constructor(name) {
    this.brand = name;
 }
  present() {
    return 'I have a ' + this.brand;
 }
}
const mycar = new Car("Ford");
mycar.present();

As shown in the example above, you call the method by using the object’s method name followed by parentheses (with parameters placed inside the parentheses if needed).

Class Inheritance

Use the extends keyword to create class inheritance, allowing a class to access all methods from its parent class.

Example

Define a class named “Model” that inherits methods from the “Car” class:

class Car {
 constructor(name) {
    this.brand = name;
 }

 present() {
    return 'I have a ' + this.brand;
 }
}

class Model extends Car {
 constructor(name, mod) {
    super(name);
    this.model = mod;
 } 
  show() {
      return this.present() + ', it is a ' + this.model
 }
}
const mycar = new Model("Ford", "Mustang");
mycar.show();

The super() method references the parent class, allowing access to its constructor and properties by calling it within the child class’s constructor.