fork download
  1. /*
  2. JavaScrit es el único lenguaje de programación
  3. que soporta programación basadae en prototipos.
  4. En el siguiente código se muestra el hecho de que,
  5. en realidad, las clases son objetos, y el uso
  6. de herencia por delegación.
  7. */
  8.  
  9.  
  10.  
  11. function Entity(type, name) {
  12. this._type = type;
  13. this._name = name;
  14.  
  15. // Object.getPrototypeOf( this ) == this.__proto__
  16. Object.getPrototypeOf( this ).type = function() { return this._type; };
  17. Object.getPrototypeOf( this ).name = function() { return this._name; };
  18.  
  19. Object.getPrototypeOf( this ).str = function() {
  20. return "Soy un " + this.type() + " y me llamo " + this.name();
  21. }
  22. }
  23.  
  24. function Warrior(type, name) {
  25. this._type = type;
  26. this._name = name;
  27.  
  28. Object.getPrototypeOf( this ).str = function() {
  29. return "Soy un guerrero " + this.type() + ". ¡Soy " + this.name() + "!";
  30. }
  31.  
  32. Object.getPrototypeOf( this ).attak = function(x) {
  33. if ( !( x instanceof Entity ) ) {
  34. return "¡No puedes atacar a eso!";
  35. }
  36.  
  37. return x.name() + "!! Raarrrrr!!";
  38. }
  39. }
  40.  
  41. // Warrior deriva de Ser
  42. Warrior.prototype.__proto__ = Entity.prototype;
  43.  
  44. let v1 = new Entity( "Vegano", "Gaggen" );
  45. let g1 = new Warrior( "Kyndr", "Rork" );
  46. let txt = v1.str();
  47.  
  48. txt += "\n" + g1.str();
  49. txt += "\n\n" + g1.attak( "Gaggen" );
  50. txt += "\n" + g1.attak( v1 );
  51. txt += "\n\nEl prototipo padre del guerrero es el del vegano: "
  52. + ( ( g1.__proto__.__proto__ == v1.__proto__ )? "sí" : "no" );
  53. txt += "\n\n" + g1.name() + " instanceof Chr: "
  54. + ( ( g1 instanceof Entity )? "sí" : "no" );
  55. txt += "\n\n" + g1.name() + " instanceof Warrior: "
  56. + ( ( g1 instanceof Warrior)? "sí" : "no" );
  57.  
  58. txt += "\n\n" + v1.name() + " instanceof Chr: "
  59. + ( ( v1 instanceof Entity )? "sí" : "no" );
  60. txt += "\n\n" + v1.name() + " instanceof Warrior: "
  61. + ( ( v1 instanceof Warrior)? "sí" : "no" );
  62.  
  63. print( txt );
  64.  
Success #stdin #stdout 0.03s 16860KB
stdin
Standard input is empty
stdout
Soy un Vegano y me llamo Gaggen
Soy un guerrero Kyndr. ¡Soy Rork!

¡No puedes atacar a eso!
Gaggen!! Raarrrrr!!

El prototipo padre del guerrero es el del vegano: sí

Rork instanceof Chr: sí

Rork instanceof Warrior: sí

Gaggen instanceof Chr: sí

Gaggen instanceof Warrior: no