JavaScript OOP
Telerik Software Academy
http://academy.telerik.com- What is inheritance
- Inheritance in ES6
- Super class calls
- Inheritance allows child classes to inherit the characteristics of an existing parent (base) class
- Attributes (fields and properties)
- Operations (methods)
- Child class can extend the parent class
- Add new fields and methods
- Redefine methods (modify existing behavior)
- Inheritance has a lot of benefits
- Extensibility
- Reusability (
code reuse) - Provides abstraction
- Eliminates redundant code
- Use inheritance for building
is-arelationships- E.g. dog
is-aanimal (dogs are kind of animals)
- E.g. dog
- Don't use it to build
has-arelationship- E.g. dog
has-aname (dog is not kind of name)
- E.g. dog
- Inheritance implicitly gains all members from another class
- All fields, methods, properties, events, …
- Some members could be inaccessible (hidden)
- The class whose methods are inherited is called base (parent) class
- The class that gains new functionality is called derived (child) class
- ES6 introduces classes and a way to create classical OOP
- Using the
classkeyword
- Using the
class Mammal {
constructor(age) {
this._age = age;
}
}- Sub classing is done using the
extendkeyword
class Mammal {
speak(str) {
// mammals usually don't speak
}
}
class Person extends Mammal {
speak(str) {
console.log(str);
}
}superis used to refer to the parent classsuper()calls the parent constructor- needed in order for
thisto refer to the correct object
- needed in order for
super.method()calls.method()from the parent class
class Person extends Mammal {
constructor(fname, lname, age) {
super(age);
this._fname = fname;
this._lname = lname;
}
get fullname() {
// getter property of fullname
}
set fullname(newfullname) {
// setter property of fullname
}
// more class members…
}Constructor of the class
Getters and setters
- "Web Design with HTML 5, CSS 3 and JavaScript" course @ Telerik Academy
- javascript course
- Telerik Software Academy
- Telerik Academy @ Facebook
- Telerik Software Academy Forums