Foros del Web » Programando para Internet » Javascript »

POO - Herencia

Estas en el tema de POO - Herencia en el foro de Javascript en Foros del Web. Alguien me podría indicar cómo podría realizar de otra manera la Herencia en el siguiente código: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código Javascript : Ver original var Person ...
  #1 (permalink)  
Antiguo 05/09/2013, 13:12
 
Fecha de Ingreso: marzo-2008
Mensajes: 1.020
Antigüedad: 16 años, 1 mes
Puntos: 21
POO - Herencia

Alguien me podría indicar cómo podría realizar de otra manera la Herencia en el siguiente código:

Código Javascript:
Ver original
  1. var Person = (function(win, doc, undefined) {
  2.    
  3.     var Person = function(fname, lname) {
  4.         this.fname = fname;
  5.         this.lname = lname;
  6.     };
  7.  
  8.     Person.prototype = {
  9.         constructor : Person,
  10.         toString : function() {
  11.             return this.fname + " " + this.lname;
  12.         },
  13.         getName : function() {
  14.             return this.fname;
  15.         },
  16.         setName : function(name) {
  17.             this.fname = name;
  18.         }
  19.     };
  20.  
  21.     return Person;
  22.  
  23.  
  24. })(window, document);
  25.  
  26.  
  27.  
  28. var User = (function(win, doc, undefined) {
  29.    
  30.     var User = function(role) {
  31.         this.role = role;
  32.     };
  33.  
  34.     User.prototype = {
  35.         constructor : User,
  36.         getRole : function() {
  37.             return this.role;
  38.         },
  39.  
  40.         setRole : function(role) {
  41.             this.role = role;
  42.         }
  43.     };
  44.  
  45.     return User;
  46.  
  47.  
  48. })(window, document);
  49.  
  50. // Aquí aplica la Herencia
  51. User.prototype = new Person('Juan', 'Garcia');
  52.  
  53. var jc = new User('admin');
  54. jc.setName('Juan Carlos');
  55.  
  56. console.log(jc);

Si tienen algun link, libro, para recomendar de JS y POO se los agradecería.
__________________
_
  #2 (permalink)  
Antiguo 05/09/2013, 15:42
Avatar de Aijoona
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Buenos Aires
Mensajes: 779
Antigüedad: 13 años
Puntos: 343
Respuesta: POO - Herencia

Por que necesitarias otra forma/manera?
__________________
blog | @aijoona
  #3 (permalink)  
Antiguo 06/09/2013, 10:37
 
Fecha de Ingreso: septiembre-2009
Ubicación: Neuquén
Mensajes: 142
Antigüedad: 14 años, 7 meses
Puntos: 12
Respuesta: POO - Herencia

Yo me siento bastante cómodo utilizando este simple script:

Código Javascript:
Ver original
  1. /**
  2.  * Simple JavaScript Inheritance
  3.  * Inspired by base2 and Prototype
  4.  * By John Resig http://ejohn.org/
  5.  * MIT Licensed.
  6.  */
  7. (function() {
  8.     var initializing = false,
  9.         fnTest = /xyz/.test(function(){xyz;})
  10.             ? /\b_super\b/
  11.             : /.*/;
  12.    
  13.     this.Class = function(){};
  14.    
  15.     Class.extend = function(prop)
  16.     {
  17.         var _super = this.prototype;
  18.        
  19.         initializing = true;
  20.         var prototype = new this();
  21.         initializing = false;
  22.        
  23.         for (var name in prop) {
  24.             prototype[name] = typeof prop[name] == "function"
  25.                 && typeof _super[name] == "function"
  26.                 && fnTest.test(prop[name])
  27.                 ? (function(name, fn) {
  28.                     return function() {
  29.                         var tmp = this._super;
  30.                         this._super = _super[name];
  31.                         var ret = fn.apply(this, arguments);       
  32.                         this._super = tmp;
  33.                        
  34.                         return ret;
  35.                     };
  36.                 })(name, prop[name])
  37.                 : prop[name];
  38.         }
  39.        
  40.         function Class() {
  41.             if ( !initializing && this.init )
  42.             this.init.apply(this, arguments);
  43.         }
  44.        
  45.         Class.prototype = prototype;
  46.         Class.prototype.constructor = Class;
  47.         Class.extend = arguments.callee;
  48.        
  49.         return Class;
  50.     };
  51. })();

La propiedad "init" es el utilizada como constructor. Ejemplos:
Código Javascript:
Ver original
  1. var Person = Class.extend({
  2.     init: function(isDancing){
  3.         this.dancing = isDancing;
  4.     },
  5.     dance: function(){
  6.         return this.dancing;
  7.     }
  8. });
  9.  
  10. var Ninja = Person.extend({
  11.     init: function(){
  12.         this._super( false );
  13.     },
  14.     dance: function(){
  15.         // Call the inherited version of dance()
  16.         return this._super();
  17.     },
  18.     swingSword: function(){
  19.         return true;
  20.     }
  21. });
  22.  
  23. var p = new Person(true);
  24. p.dance(); // => true
  25.  
  26. var n = new Ninja();
  27. n.dance(); // => false
  28. n.swingSword(); // => true
  29.  
  30. // Should all be true
  31. p instanceof Person && p instanceof Class &&
  32. n instanceof Ninja && n instanceof Person && n instanceof Class

Fuente: http://ejohn.org/blog/simple-javascript-inheritance/

Saludos.
__________________
Amigos de Foros del Web: seamos más solidarios. ¡No dejemos que un tema se valla al final de las páginas con 0 (cero) respuestas! ¡Gracias por su ayuda! :-)
  #4 (permalink)  
Antiguo 07/09/2013, 19:28
 
Fecha de Ingreso: marzo-2008
Mensajes: 1.020
Antigüedad: 16 años, 1 mes
Puntos: 21
Respuesta: POO - Herencia

Muchas Gracias por responder.

Cita:
Iniciado por Aijoona Ver Mensaje
Por que necesitarias otra forma/manera?
Porque quiero tratar de ordenar el código JS, tener una mejor opción o alternativa ya probada y evitar usar alguna librería como Backbonejs. Por lo menos de momento.

-----------------------------

Acá les dejo unos cambios que hice sin utilizar métodos como los que plantea "Nisrokh". No se cuáles son las limitaciones de momento.

Ver princcipalmente la clase "Triangulo".

Código:

Código Javascript:
Ver original
  1. var Figura = (function(win, doc, undefined) {
  2.     'use strict'
  3.    
  4.     var Figura = function(base, altura) {
  5.         this.base = base;
  6.         this.altura = altura;
  7.     }
  8.  
  9.    
  10.     Figura.prototype = {
  11.            
  12.         constructor : Figura,
  13.        
  14.         area : function() {
  15.             return this.base * this.altura;
  16.         },
  17.        
  18.         perimetro : function() {
  19.             return ( (this.base * 2) + (this.altura * 2) );
  20.         }
  21.     };
  22.    
  23.     // Private
  24.     var _perimetro = function(context) {
  25.         return 'Perímetro';
  26.     };
  27.    
  28.     return Figura;
  29.    
  30. })(window, document);
  31.  
  32.  
  33. // Herencia, Polimorfismo y Sobrescritura -> ¿Cómo?
  34. // class Circulo extends Figura {}; -> Java, PHP, etc.
  35.  
  36. var Circulo = (function(win, doc, undefined) {
  37.     'use strict'
  38.    
  39.     var Circulo = function(radio) {
  40.         this.radio = radio;
  41.     }
  42.    
  43.     Circulo.prototype = {
  44.         constructor : Circulo,
  45.        
  46.         area : function() {
  47.             return ( Math.pow( (Math.PI * this.radio), 2) );
  48.         }
  49.     };
  50.    
  51.     return Circulo;
  52.    
  53. })(window, document);
  54.  
  55.  
  56. // Herencia
  57. Circulo.prototype = new Figura(40, 80);
  58. var circulito = new Circulo(5);
  59.  
  60.  
  61.  
  62. // Triangulo
  63. var Triangulo = (function(win, doc, undefined) {
  64.     'use strict'
  65.    
  66.     // Private Properties
  67.     var name = "";
  68.    
  69.     // Constructor
  70.     var Triangulo = function(base, altura, angulo, fname) {
  71.         Figura.call(this, base, altura);
  72.        
  73.         // Set Private Property
  74.         name = fname;
  75.        
  76.         // Set Public Property
  77.         this.angulo = angulo;
  78.        
  79.         // Setters and Getters
  80.         this.getName = function() {
  81.             return name;
  82.         }
  83.        
  84.         // Public Methods
  85.         this.getAngulo = function() {
  86.             return this.angulo;
  87.         };
  88.        
  89.         // Sobreescritura ? - check
  90.         // Si no esta este método se utiliza el de Figura
  91.         this.area = function() {
  92.             return ( (this.base * this.altura) / 2);
  93.         },
  94.        
  95.         // Polimorfismo ? - check
  96.         /*this.area = function(base, altura) {
  97.             return ( (base * altura) / 2);
  98.         },*/
  99.        
  100.         this.doSomething = function() {
  101.             return _doSomethingFine();
  102.         }
  103.        
  104.     }
  105.    
  106.     // Private Methods
  107.    
  108.     var _doSomethingFine = function() {
  109.         return 'Do something Fine';
  110.     }
  111.    
  112.     return Triangulo;
  113.    
  114. })(window, document);
  115.  
  116. // Herencia
  117. Triangulo.prototype = new Figura();
  118. var triangulo = new Triangulo(5, 8, 45, 'Nombre Completo');
  119. console.log(triangulo)
  120. console.log('Triangulo - Something => ', triangulo.doSomething());
  121. console.log('Triangulo - Área   => ', triangulo.area());
  122. console.log('Nombre-> ', triangulo.getName());
__________________
_
  #5 (permalink)  
Antiguo 09/09/2013, 08:30
Avatar de Aijoona
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Buenos Aires
Mensajes: 779
Antigüedad: 13 años
Puntos: 343
Respuesta: POO - Herencia

Tu implementación está rota, tenés una unica variable para multiples instancias (name):

Código Javascript:
Ver original
  1. var a = new Triangulo(10, 10, 60, 'a');
  2. var b = new Triangulo(10, 10, 60, 'b');
  3.  
  4. a.getName(); // b

Te diría que te esfuerzes mas en entender como funciona JavaScript más que en manipularlo y aplastarlo para parecerse a otros lenguajes muy distintos.

Funciones privadas? Si algo es privado no lo accedas.
Polimorfismo? Si, un poco más laxo por falta de interfaces, pero igual de util.
Herencia? Si, hay mecanismos del lenguaje que lo permiten.
Override? Tan sencillo como declarar un metodo/property en el objeto actual o en algun prototipo mas cercano.
__________________
blog | @aijoona
  #6 (permalink)  
Antiguo 09/09/2013, 16:26
 
Fecha de Ingreso: marzo-2008
Mensajes: 1.020
Antigüedad: 16 años, 1 mes
Puntos: 21
Respuesta: POO - Herencia

Cita:
Override? Tan sencillo como declarar un metodo/property en el objeto actual o en algun prototipo mas cercano.
Figura.js
Código Javascript:
Ver original
  1. var Figura = (function(win, doc, undefined) {
  2.     'use strict'
  3.    
  4.     var Figura = function(base, altura) {
  5.         this.base = base;
  6.         this.altura = altura;
  7.     }
  8.  
  9.    
  10.     Figura.prototype = {
  11.            
  12.         constructor : Figura,
  13.        
  14.         area : function() {
  15.             return this.base * this.altura;
  16.         },
  17.        
  18.         perimetro : function() {
  19.             return ( (this.base * 2) + (this.altura * 2) );
  20.         }
  21.     };
  22.  
  23.    
  24.     return Figura;
  25.    
  26. })(window, document);

Triangulo.js
Código Javascript:
Ver original
  1. var Triangulo = (function(win, doc, undefined) {
  2.     'use strict'
  3.    
  4.     var Triangulo = function() {
  5.        
  6.     };
  7.    
  8.     Triangulo.prototype =  {
  9.         constructor : Triangulo
  10.        
  11.        
  12.     };
  13.  
  14.     return Triangulo;
  15.    
  16. })(window, document);

Main.js
Código Javascript:
Ver original
  1. Triangulo.prototype = new Figura(10, 20);
  2.  
  3. Triangulo.prototype.area = function() {
  4.     alert('area triangulo');
  5. }
  6.  
  7. var triangulo = new Triangulo();
  8.  
  9. triangulo.area();
  10.  
  11. console.log(triangulo)

¿De esta Manera Planteas hacer un Overwrait de un métodos?

Me recomiendas un libro o enlaces para ver todo eso que comentas.
__________________
_

Última edición por opzina; 09/09/2013 a las 17:38
  #7 (permalink)  
Antiguo 10/09/2013, 08:32
Avatar de Aijoona
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Buenos Aires
Mensajes: 779
Antigüedad: 13 años
Puntos: 343
Respuesta: POO - Herencia

Si definis el metodo area en Triangulo ya hiciste un override, ya que la instancia va llamar al codigo especifico de Triangulo en lugar del de Figura.

Graficamente el override seria como (vease metodo saludar):


__________________
blog | @aijoona

Etiquetas: herencia, js, poo
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:12.