Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement