Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//Inheritance example in js
class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}
Area() {
return this.length * this.width;
}
}
const FirstRectangle = new Rectangle(2, 3);
console.log(FirstRectangle.Area());
//extending to square
class Square extends Rectangle {
constructor(side) {
super(side, side);
}
}
const FirstSquare = new Square(2);
console.log(FirstSquare.Area());
//Another example
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
greeting() {
return `Hi! I'm ${this.name}`;
}
farewell() {
return `${this.name} has left the building. Bye for now!`;
}
}
const Amy = new Person("Amy", 19, "female");
Amy.farewell();
//extending to Teacher
class Teacher extends Person {
constructor(name, age, gender, subject) {
super(name, age, gender);
this.subject = subject;
}
}
let snape = new Teacher("Severus", 58, "male", "Dark arts");
snape.greeting();
@vaibhav-kumar-tokyo

This comment has been minimized.

Copy link

@vaibhav-kumar-tokyo vaibhav-kumar-tokyo commented Dec 5, 2020

return this.length * this.width

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment