Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active December 8, 2020 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShilpiMaurya/1eeaf62506d5616505a116e33a917fbf to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/1eeaf62506d5616505a116e33a917fbf to your computer and use it in GitHub Desktop.
//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();
@vbkmr
Copy link

vbkmr 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