Objects - marinakosova/master-the-coding-interview GitHub Wiki
Object-oriented Programming in JavaScript: Made Super Simple
JavaScript Object Oriented Programming Tutorial Beginners - OOP in JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
}
const firstPerson = new Person('Marina', 19);
console.log(firstPerson.name);
// or
console.log(firstPerson.getName());
class House {
constructor(price, residents) {
this.price = price;
this.residents = residents;
}
getPrice() {
return this.price;
}
getResidents() {
return this.residents;
}
addResidents(resident) {
this.residents.push(resident);
}
}
let alex = new Person('Alex', 23);
let michael = new Person('Mikhael', 18);
const firstHouse = new House(320, [alex, michael]);
console.log(firstHouse.getResidents()); // [Person, Person]
let pavel = new Person('Pavel', 19);
firstHouse.addResidents(pavel);
console.log(firstHouse.getResidents()); // [Person, Person, Person]
// Abstraction: hiding implementation of complex piece of code
firstHouse.addResidents(new Person('Alexey', 11)); // means I don't neet to know about code inside Person class
// Incapsulation
// mark for example your variable with underscore< so other developers will know, that they don't need to touch it
// For example
// class Person {
// constructor(name, age) {
// this._name = name;
// this._age = age;
// }
// }
// Inheritance
// class Programmer {
// constructor(company, salary) {
// this.company = company;
// this.salary = salary;
// }
// sayHi() {
// console.log(`Hello, I am a programmer! I work for ${this.company}`);
// }
// }
// let firstProgrammer = new Programmer('Meta', 1000);
// firstProgrammer.sayHi();
// to be able to use inheritance say that programmer extends Person (we have access to everything Person has)
class Programmer extends Person {
constructor(name, age, company, salary) {
super(name, age);
this.company = company;
this.salary = salary;
}
sayHi() {
console.log(`Hello, I am a programmer! My name is ${this.getName()}. I work for ${this.company}`);
}
}
let firstProgrammer = new Programmer('Meta', 1000);
firstProgrammer.sayHi();
// Polymorphism
const name = 'Alex'; // Js guessing what type is actually a name and it can be any type(form)
// so Polymorphism is when something can принимать diff forms
class Doctor extends Person { // Person can be any type: doctor, teacher...
constructor(name, age, degree) {
super(name, age);
this.degree = degree;
}
}