Skip to content

Instantly share code, notes, and snippets.

@shahbazsyed
Created April 25, 2017 08:36
Show Gist options
  • Save shahbazsyed/fa192c0ff3e6720fa1efed8763a2d8eb to your computer and use it in GitHub Desktop.
Save shahbazsyed/fa192c0ff3e6720fa1efed8763a2d8eb to your computer and use it in GitHub Desktop.
Inherting from Prototype in Js
/*
This gist covers creating a subclass from a baseclas, overriding in the prototype chain, and adding properties
to the master Object prototype
*/
// baseclass
var Job = function() {
this.pays = true;
};
// add print method to the Job prototype
Job.prototype.print = function() {
console.log(this.pays ? 'Good' : 'Bad');
};
// creating a subclass object TechJob from the baseclass Job
var TechJob = function(title, pays) {
/*
Calls the constructor of Job and makes it the parent of TechJob class.
But, we haven't inherited the print method yet from Job!
*/
Job.call(this);
this.title = title;
this.pays = pays;
};
// Inheriting method from the prototype of parent class
TechJob.prototype = Object.create(Job.prototype);
/*
Set the constructor of TechJob to the TechJob we created above(Because this has the call to Job constructor)
*/
TechJob.prototype.constructor = TechJob; //
// Overriding the print method in our subclass
TechJob.prototype.print = function(){
console.log(this.pays?this.title+' is a Nice TechJob':this.title+' is a Bad TechJob');
};
var softwareDeveloper = new TechJob('JsDev', true);
var phpDeveloper = new TechJob('phpDev',false);
console.log(softwareDeveloper.print());
console.log(phpDeveloper.print());
// To add a method to main parent Object class
Object.prototype.printToConsole = function(){
console.log("This is from the master!");
};
console.log(softwareDeveloper.printToConsole()); // From the master!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment