Classic Class Prototype Inheritance


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Extends a sub class from a super class.
  3.  * @param {Function} subClass The subclass.
  4.  * @param {Function} superClass The super class to extend.
  5.  */
  6. function extends(subClass, superClass) {
  7. var midClass = function() {
  8. };
  9. midClass.prototype = superClass.prototype;
  10. subClass.prototype = new midClass();
  11. subClass.superClass = superClass;
  12. }
  13.  
  14. /**
  15.  * A person.
  16.  * @constructor
  17.  * @param {string} name
  18.  */
  19. function Person(name) {
  20. /**
  21.   * @private {string}
  22.   */
  23. this._name = name;
  24. }
  25.  
  26.  
  27. /**
  28.  * @return {string}
  29.  */
  30. Person.prototype.getName = function() {
  31. return this._name;
  32. };
  33.  
  34. /**
  35.  * A user.
  36.  * @constructor
  37.  * @inheritDoc
  38.  * @extends {Person}
  39.  */
  40. function User(name) {
  41. User.superClass.call(this, name);
  42. }
  43. extends(User, Person);
  44.  
  45.  
  46. /**
  47.  * @return {number}
  48.  */
  49. User.prototype.getNameLength = function() {
  50. return this.getName().length;
  51. };
  52.  
  53. // Demo
  54. var user = new User('John Doe');
  55. user.alertName(); // John Doe
  56. document.writeln(user.getName()); // John Doe
  57. document.writeln(user instanceof User); // true;
  58. document.writeln(user instanceof Person); // true;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.