Šajā apmācībā jūs uzzināsit par JavaScript klases mantošanu, izmantojot piemērus.
Klases mantojums
Mantošana ļauj definēt klasi, kas pārņem visu vecāku klases funkcionalitāti, un ļauj pievienot vairāk.
Izmantojot klases mantojumu, klase var mantot visas citas klases metodes un īpašības.
Mantošana ir noderīga funkcija, kas ļauj atkārtoti izmantot kodu.
Lai izmantotu klases mantojumu, izmantojiet extends
atslēgvārdu. Piemēram,
// parent class class Person ( constructor(name) ( this.name = name; ) greet() ( console.log(`Hello $(this.name)`); ) ) // inheriting parent class class Student extends Person ( ) let student1 = new Student('Jack'); student1.greet();
Rezultāts
Sveiks Džek
Iepriekš minētajā piemērā Student
klase pārmanto visas klases metodes un īpašības Person
. Tādējādi Student
klasei tagad būs name
īpašums un greet()
metode.
Pēc tam mēs piekļuvām klases greet()
metodei, Student
izveidojot student1
objektu.
JavaScript super () atslēgvārds
super
Atslēgvārds izmanto iekšpuses bērnu klasi apzīmē tās mātes klasi. Piemēram,
// parent class class Person ( constructor(name) ( this.name = name; ) greet() ( console.log(`Hello $(this.name)`); ) ) // inheriting parent class class Student extends Person ( constructor(name) ( console.log("Creating student class"); // call the super class constructor and pass in the name parameter super(name); ) ) let student1 = new Student('Jack'); student1.greet();
Šeit super
iekšējā Student
klase attiecas uz Person
klasi. Tādējādi, ja Student
tiek izsaukts klases konstruktors , tas izsauc arī Person
klases konstruktoru, kas tam piešķir nosaukuma rekvizītu.
Svarīgākā metode vai īpašums
Ja bērnu klasei ir tāda pati metode vai rekvizīta nosaukums kā vecāku klasei, tā izmantos bērnu klases metodi un rekvizītu. Šo jēdzienu sauc par metodes ignorēšanu. Piemēram,
// parent class class Person ( constructor(name) ( this.name = name; this.occupation = "unemployed"; ) greet() ( console.log(`Hello $(this.name).`); ) ) // inheriting parent class class Student extends Person ( constructor(name) ( // call the super class constructor and pass in the name parameter super(name); // Overriding an occupation property this.occupation = 'Student'; ) // overriding Person's method greet() ( console.log(`Hello student $(this.name).`); console.log('occupation: ' + this.occupation); ) ) let p = new Student('Jack'); p.greet();
Rezultāts
Sveiks, students Džek. nodarbošanās: Students
Šeit occupation
īpašums un greet()
metode ir vecāku Person
klasē un bērnu Student
klasē. Tādējādi Student
klase ignorē occupation
rekvizītu un greet()
metodi.
Mantojuma izmantošana
- Tā kā bērnu klase var mantot visas vecāku klases funkcijas, tas ļauj kodu atkārtoti izmantot.
- Kad funkcionalitāte ir izstrādāta, varat to vienkārši pārmantot. Nav nepieciešams no jauna izgudrot riteni. Tas ļauj tīrāku kodu un vieglāk uzturēt.
- Tā kā bērnu klasē varat pievienot arī savas funkcijas, varat mantot tikai noderīgās funkcijas un definēt citas nepieciešamās funkcijas.