Created
November 19, 2018 07:26
-
-
Save emfluenceindia/e8a24a20ccd689ff9729997f35197c60 to your computer and use it in GitHub Desktop.
ES6 - A basic example of JavaScript class and inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Declaring Person class, its constructor and methods. | |
This class will be inherited by GetPerson class later to access its properties and methods. | |
*/ | |
class Person { | |
constructor(person) { | |
this.name = person.name; | |
this.jobTitle = person.jobTitle; | |
this.location = person.location; | |
this.skillSet = person.skill; | |
} | |
getPerson = () => { | |
const objPerson = { | |
name: this.name, | |
jobTitle: this.jobTitle, | |
} | |
return (objPerson); | |
} | |
getPersonLocation = () => { | |
return this.location; | |
} | |
getPersonSkill = () => { | |
return this.skillSet; | |
} | |
} | |
/** | |
class GetPerson inherits Person | |
*/ | |
class GetPerson extends Person { | |
personInfo () { | |
const thisPerson = this.getPerson(); | |
const thisPersonLocation = this.getPersonLocation(); | |
const thisPersonSkill = this.getPersonSkill(); | |
const vCard = ` | |
Person Information: | |
------------------------------- | |
${thisPerson.name} | |
Job title: ${thisPerson.jobTitle} | |
${thisPersonLocation.city}, ${thisPersonLocation.country} | |
Skill set: ${thisPersonSkill}`; | |
console.log(vCard); | |
} | |
} | |
/** | |
Build a JavaScript object to pass to parent class Person | |
which then will be interited by class GtePerson class. | |
*/ | |
const objPerson = { | |
name: 'Subrata Sarkar', | |
jobTitle: 'Web developer', | |
skill: [ | |
'WordPress', | |
'React', | |
'ES6', | |
'C#', | |
'MVC' | |
], | |
location: { | |
city: 'Kolkata', | |
country: 'India' | |
} | |
} | |
// Create a new instance of GetPerson class | |
const getPerson = new GetPerson( objPerson ); | |
/** | |
Call personInfo() method declared inside GetPerson class | |
since GetPerson extends Person, it has automatic acccess to the | |
object and methods inside Person class. | |
*/ | |
getPerson.personInfo(); | |
/** | |
Output | |
Person Information: | |
------------------------------- | |
Subrata Sarkar | |
Job title: Web developer | |
Kolkata, India | |
Skill set: WordPress,React,ES6,C#,MVC | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment