⊗jsOpIhOPM 31 of 60 menu

Overriding Parent Methods in OOP in JavaScript

A child class can override a parent method by creating a method with the same name. Let's look at an example. Let's say we have the following parent class:

class User { setName(name) { this.name = name; } getName() { return this.name; } }

Let's create a method of the same name in the descendant class:

class Student extends User { setName(name) { } }

As a rule, overriding parent methods is needed to change or supplement the behavior of this method. Let's add a name length check in our case:

class Student extends User { setName(name) { if (name.length > 0) { this.name = name; } else { throw new Error('student name error'); } } }

Let's make sure that it is the overridden method that is called. First, let's create an object of the descendant class:

let student = new Student;

Now let's call our method, passing it the correct value:

student.setName('john');

Now let's call the method, passing an incorrect value to it. As a result, we will see the error thrown in the console:

student.setName(''); // error mistake fault flaw fallacy miscarriage failing lapse slip trip misstep inaccuracy gaffe faux pas break stumble lapsus misdeed bungle misdoing muff clinker floater X slip-up chance-medley

In the User class, make an age getter and setter.

In the Employee class, override the age setter and make it check that the age is from 18 to 65 years old.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline