Posted By

marcio on 03/10/09


Tagged

javascript class oop


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Bolek


Javascript OOP


 / Published in: JavaScript
 

URL: http://www.anieto2k.com/2009/03/10/mejorando-rendimientos-de-las-tecnicas-de-poo-en-javascript/

Para crear clases en javascript, y poder extenderlas y jugar con ellas

  1. var Klass = function(prop) {
  2. var klass = function(){ if(this.init) this.init.apply(this, arguments);};
  3. klass.prototype = prop || {};
  4. klass.constructor = Klass;
  5. klass.extend = Klass.extend;
  6. return klass;
  7. };
  8.  
  9. Klass.extend = function(prop){
  10. function setParent(fn, parent) {
  11. return function() {
  12. this.parent = parent;
  13. return fn.apply(this, arguments);
  14. }
  15. }
  16. function merge(prev, next){
  17. for (var name in next){
  18. if (prev[name] && (typeof prev[name] == 'object' && typeof next[name] == 'object'))
  19. merge(prev[name], next[name]);
  20. else
  21. prev[name] = next[name];
  22. }
  23. return prev;
  24. };
  25.  
  26. for (var name in this.prototype) {
  27. if (!prop[name])
  28. prop[name] = this.prototype[name];
  29. else if(typeof prop[name] == 'function' && typeof this.prototype[name] == 'function')
  30. prop[name] = setParent(prop[name], this.prototype[name]);
  31. else if(typeof prop[name] == 'object' && typeof this.prototype[name] == 'object')
  32. prop[name] = merge(prop[name], this.prototype[name]);
  33. }
  34. return new Klass(prop);
  35. };
  36.  
  37. //Modo de uso
  38. var Hobbit = Klass({
  39. bailar: function(){
  40. .....
  41. }
  42. });
  43.  
  44. var Frodo = Hobbit.extend({
  45. anillo: true;
  46. desaparecer: function(){
  47. if (this.anillo)
  48. this.display("none");
  49. }
  50. });

Report this snippet  

You need to login to post a comment.