Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

71
Views
how to call the methods of a parent class in a child class object without overriding in child in java script

Let's say I have a parent and a child class as shown below.

class Person { 

  constructor(name) { 
    this.name = name
  }

  greeting() { 
    console.log(`Hi! I'm ${this.name}`); 
  };

}

class Teacher extends Person { 
  constructor(first, subject) { 
    super(first); 

    this.subject = subject; 
  }
}

now lets say I create a global object of the child class

globalThis.teachers = new Teacher("Roby", "Math") 

this global object can directly access the parent class property name. So, I can call,

globalThis.teachers.name \\Will contain Roby

But can I call the method of the parent class, greeting() like this directly without overriding it like the following way?

globalThis.teachers.greeting() \\Will print in console

Snippet:

class Person { 

  constructor(name) { 
    this.name = name
  }

  greeting() { 
    console.log(`Hi! I'm ${this.name}`); 
  };

}

class Teacher extends Person { 
  constructor(first, subject) { 
    super(first); 

    this.subject = subject; 
  }
}

globalThis.teachers = new Teacher("Roby", "Math") 
console.log(globalThis.teachers.name);
globalThis.teachers.greeting();

Is it like every parent class method that I want to access, I will have to override it in the child and from there I will have to call super.greeting().

7 months ago ยท Santiago Trujillo
Answer question
Find remote jobs