Posted By

seba_dom on 01/10/13


Tagged

extending heritance implementations


Versions (?)

Implements


 / Published in: JavaScript
 

Prototipal heritance and leaving trail of implementations

  1. N = {};
  2.  
  3. var myExtend = function (destination/**, supers */) {
  4. var supers = Array.prototype.slice.call(arguments, 1);
  5. var implementations = destination.implementations || [];
  6.  
  7. var registerInheritance = function (target, source) {
  8. if (source.constructor !== Object &&
  9. !_.include(implementations, source)) {
  10. implementations.push(source);
  11. }
  12. };
  13.  
  14. _.each(supers, function (localSuper) {
  15. registerInheritance(destination, localSuper);
  16. _.extend(destination, localSuper);
  17. });
  18.  
  19. if (implementations.length > 0) {
  20. destination.implementations = implementations;
  21. }
  22.  
  23. return destination;
  24. };
  25.  
  26. var implements = function (obj, prototype) {
  27. var doImplements = false;
  28. var implementationStack = [];
  29. var getImplementations = function (source) {
  30. _.each(source.implementations, function (localImplementation) {
  31. var notIncluded = !_.any(implementationStack, function (i) {
  32. return _.isEqual(localImplementation, i);
  33. });
  34. if (notIncluded) {
  35. implementationStack.push(localImplementation);
  36. }
  37. if (localImplementation.implementations &&
  38. localImplementation.implementations.length > 0) {
  39. getImplementations(localImplementation);
  40. }
  41. });
  42. };
  43. getImplementations(obj);
  44. doImplements = _.any(implementationStack, function (implementation) {
  45. return implementation.constructor === prototype;
  46. });
  47. console.log(implementationStack);
  48. return doImplements;
  49. };
  50. N.sup = function () {
  51. return myExtend(this, {
  52. sup: 'this'
  53. });
  54. };
  55. N.Base = function () {
  56. var sup = new N.sup();
  57. return myExtend(this, sup, {
  58. base: 'base'
  59. });
  60. };
  61.  
  62. N.Gadget = function () {
  63. var base = new N.Base();
  64. return myExtend(this, base, {
  65. bla: 'bla'
  66. });
  67. };
  68.  
  69. N.middleG = function () {
  70. var base = new N.Base();
  71. return myExtend(this, base, {
  72. lala: 'lala'
  73. });
  74. };
  75.  
  76. N.GadgetInterface = function () {
  77. return myExtend(this, {
  78. i: 'interface'
  79. });
  80. };
  81.  
  82. N.myGadget = function () {
  83. var i = new N.GadgetInterface();
  84. var g = new N.Gadget();
  85. var gm = new N.middleG();
  86. return myExtend(this, i, g, gm, { foo:'foo' });
  87. };
  88.  
  89. var s = new N.myGadget();
  90.  
  91. console.log(s);
  92. console.log(implements(s, N.sup));
  93. console.log(implements(s, N.Base));
  94. console.log(implements(s, N.Gadget));
  95. console.log(implements(s, N.GadgetInterface));

Report this snippet  

You need to login to post a comment.