Created
April 25, 2017 08:36
-
-
Save shahbazsyed/fa192c0ff3e6720fa1efed8763a2d8eb to your computer and use it in GitHub Desktop.
Inherting from Prototype in Js
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
/* | |
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