Posted By

rickygri on 04/23/14


Tagged

object template oop constructor construct


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jdiprose


OOP Javascript Template with constructor and inheritance


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects

From @blixt http://stackoverflow.com/users/119081/blixt

As you can see, the classes correctly interact with each other (they share the static id from MyClass, the announce method uses the correct get_name method, etc.)

One thing to note is the need to shadow instance properties. You can actually make the inherit function go through all instance properties (using hasOwnProperty) that are functions, and automagically add a super property. This would let you call this.superget_name() instead of storing it in a temporary value and calling it bound using call.

For methods on the prototype you don't need to worry about the above though, if you want to access the super class' prototype methods, you can just call this.constructor.super.prototype.methodName. If you want to make it less verbose you can of course add convenience properties. :)

  1. /* ==========================================================================
  2.   Class template
  3.   ========================================================================== */
  4.  
  5. var MyClass = (function () {
  6. // private static
  7. var nextId = 1;
  8.  
  9. // constructor
  10. var cls = function () {
  11. // private
  12. var id = nextId++;
  13. var name = 'Unknown';
  14.  
  15. // public (this instance only)
  16. this.get_id = function () { return id; };
  17.  
  18. this.get_name = function () { return name; };
  19. this.set_name = function (value) {
  20. if (typeof value != 'string')
  21. throw 'Name must be a string';
  22. if (value.length < 2 || value.length > 20)
  23. throw 'Name must be 2-20 characters long.';
  24. name = value;
  25. };
  26. };
  27.  
  28. // public static
  29. cls.get_nextId = function () {
  30. return nextId;
  31. };
  32.  
  33. // public (shared across instances)
  34. cls.prototype = {
  35. announce: function () {
  36. alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
  37. 'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
  38. }
  39. };
  40.  
  41. return cls;
  42. })();
  43.  
  44. /* ==========================================================================
  45.   Child Class w/ Inheritance
  46.   ========================================================================== */
  47.  
  48. // It's a good idea to have a utility class to wire up inheritance.
  49. function inherit(cls, superCls) {
  50. // We use an intermediary empty constructor to create an
  51. // inheritance chain, because using the super class' constructor
  52. // might have side effects.
  53. var construct = function () {};
  54. construct.prototype = superCls.prototype;
  55. cls.prototype = new construct;
  56. cls.prototype.constructor = cls;
  57. cls.super = superCls;
  58. }
  59.  
  60. var MyChildClass = (function () {
  61. // constructor
  62. var cls = function (surName) {
  63. // Call super constructor on this instance (any arguments
  64. // to the constructor would go after "this" in call(…)).
  65. this.constructor.super.call(this);
  66.  
  67. // Shadowing instance properties is a little bit less
  68. // intuitive, but can be done:
  69. var getName = this.get_name;
  70.  
  71. // public (this instance only)
  72. this.get_name = function () {
  73. return getName.call(this) + ' ' + surName;
  74. };
  75. };
  76. inherit(cls, MyClass); // <-- important!
  77.  
  78. return cls;
  79. })();
  80.  
  81. /* ==========================================================================
  82.   Using it all w/ inheritance
  83.   ========================================================================== */
  84.  
  85. var bob = new MyClass();
  86. bob.set_name('Bob');
  87. bob.announce(); // id is 1, name shows as "Bob"
  88.  
  89. var john = new MyChildClass('Doe');
  90. john.set_name('John');
  91. john.announce(); // id is 2, name shows as "John Doe"
  92.  
  93. alert(john instanceof MyClass); // true

Report this snippet  

You need to login to post a comment.