Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. /*
  2. This gist covers creating a subclass from a baseclas, overriding in the prototype chain, and adding properties
  3. to the master Object prototype
  4. */
  5.  
  6. // baseclass
  7. var Job = function() {
  8. this.pays = true;
  9. };
  10.  
  11. // add print method to the Job prototype
  12. Job.prototype.print = function() {
  13. console.log(this.pays ? 'Good' : 'Bad');
  14. };
  15.  
  16. // creating a subclass object TechJob from the baseclass Job
  17. var TechJob = function(title, pays) {
  18. /*
  19. Calls the constructor of Job and makes it the parent of TechJob class.
  20. But, we haven't inherited the print method yet from Job!
  21. */
  22. Job.call(this);
  23. this.title = title;
  24. this.pays = pays;
  25. };
  26.  
  27. // Inheriting method from the prototype of parent class
  28. TechJob.prototype = Object.create(Job.prototype);
  29.  
  30. /*
  31. Set the constructor of TechJob to the TechJob we created above(Because this has the call to Job constructor)
  32. */
  33. TechJob.prototype.constructor = TechJob; //
  34.  
  35. // Overriding the print method in our subclass
  36.  
  37. TechJob.prototype.print = function(){
  38.  
  39. console.log(this.pays?this.title+' is a Nice TechJob':this.title+' is a Bad TechJob');
  40. };
  41.  
  42. var softwareDeveloper = new TechJob('JsDev', true);
  43. var phpDeveloper = new TechJob('phpDev',false);
  44. console.log(softwareDeveloper.print());
  45. console.log(phpDeveloper.print());
  46.  
  47. // To add a method to main parent Object class
  48. Object.prototype.printToConsole = function(){
  49. console.log("This is from the master!");
  50. };
  51.  
  52. console.log(softwareDeveloper.printToConsole()); // From the master!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement