{"id":687,"date":"2024-07-30T20:02:37","date_gmt":"2024-07-30T18:02:37","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=687"},"modified":"2024-07-30T20:02:37","modified_gmt":"2024-07-30T18:02:37","slug":"001-prototipos-en-javascript","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/05-programacion-orientada-a-objetos\/001-prototipos-en-javascript\/","title":{"rendered":"001. Prototipos en Javascript"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">En este cap\u00edtulo comenzaremos a hablar sobre una de las cosas m\u00e1s importantes en <strong>Javascript<\/strong>, y son los <strong>prototipos<\/strong>. <strong>Javascript<\/strong> es un <strong>lenguaje multiparadigma<\/strong>, es decir, podemos utilizar diferentes <strong>paradigmas de programaci\u00f3n<\/strong> (<strong>programaci\u00f3n funcional<\/strong>, <strong>programaci\u00f3n orientada a objetos<\/strong>..). A d\u00eda de hoy el <strong>paradigma<\/strong> m\u00e1s utilizado en la mayor\u00eda de lenguajes de programaci\u00f3n es el de la <strong>programaci\u00f3n orientada a objetos<\/strong> o <strong>POO<\/strong>, y una caracter\u00edstica muy importante de <strong>Javascript<\/strong> es que la <strong>orientaci\u00f3n<\/strong> <strong>a<\/strong> <strong>objetos<\/strong> en el lenguaje es muy diferente a otros lenguajes basados en <strong>clases<\/strong> como <strong>C<\/strong>, <strong>Java<\/strong>&#8230;<\/p>\n\n\n\n<!--more-->\n\n\n\n<p class=\"wp-block-paragraph\">A partir del est\u00e1ndar <strong>ES6<\/strong> ya tenemos <strong>clases<\/strong>, sin embargo dichas <strong>clases<\/strong> no son m\u00e1s que un az\u00facar sint\u00e1ctico, es decir, una manera m\u00e1s f\u00e1cil que provee <strong>Javascript<\/strong> para poder hacer la <strong>programaci\u00f3n basada en prototipos<\/strong>, es decir, aunque ya tenemos <strong>clases<\/strong> en <strong>Javascript<\/strong>, esas <strong>clases<\/strong>, el compilador del navegador las convierte a <strong>funciones protot\u00edpicas<\/strong>. Por lo tanto es muy importante entender lo que son los <strong>prototipos<\/strong> en <strong>Javascript<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conceptos de la POO<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dentro de la <strong>POO<\/strong> (<strong>programaci\u00f3n orientada a objetos<\/strong>) hay 4 conceptos muy importantes que debemos entender:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Clases<\/strong>: son modelos a seguir, es decir, algo que sirve como esquema para de ah\u00ed basarnos y poder generar <strong>instancias<\/strong>.<\/li>\n\n\n\n<li><strong>Objetos<\/strong>: es una <strong>instancia<\/strong> de una <strong>clase<\/strong>, es decir, una copia de ese modelo.\n<ul class=\"wp-block-list\">\n<li><strong>Atributos<\/strong>: son <strong>caracter\u00edsticas<\/strong> o <strong>propiedades<\/strong> del <strong>objeto<\/strong>. Son <strong>variables<\/strong> dentro de un <strong>objeto<\/strong>.<\/li>\n\n\n\n<li><strong>M\u00e9todos<\/strong>: son las acciones que un <strong>objeto<\/strong> puede realizar, son <strong>funciones<\/strong> dentro de un objeto.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prototipo en Javascript<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Un <strong>prototipo<\/strong> es un mecanismo por el cual un <strong>objeto<\/strong> puede heredar de un objeto padre <strong>atributos<\/strong> y <strong>m\u00e9todos<\/strong>. De hecho la <strong>herencia<\/strong> en <strong>Javascript<\/strong> se da mediante la cadena de <strong>prototipos<\/strong>. Por decirlo, crea una copia del <strong>prototipo<\/strong> en el cual est\u00e1 basado.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Vamos a crear un ejm generando un <strong>prototipo<\/strong> del cual nos basemos para hacer copias del mismo. Vamos a crear lo que se denomina una <strong>funci\u00f3n constructora<\/strong>, que, como su nombre dice, la vamos a construir una sola vez y a partir de ella vamos a generar nuevas <strong>instancias<\/strong> (nuevos <strong>objetos<\/strong>) que sean de este tipo de <strong>funci\u00f3n constructora.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"es\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Prototipos en Javascript&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Prototipos en Javascript&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; function Persona(nombre, genero) {\n&nbsp; &nbsp; &nbsp; &nbsp; this.nombre = nombre;\n&nbsp; &nbsp; &nbsp; &nbsp; this.genero = genero;\n&nbsp; &nbsp; &nbsp; &nbsp; this.hablar = function () {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Estoy hablando pq soy una persona\");\n&nbsp; &nbsp; &nbsp; &nbsp; };\n&nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; const francisco = new Persona(\"Francisco\", \"Macho\"),\n&nbsp; &nbsp; &nbsp; &nbsp; beatriz = new Persona(\"Beatriz\", \"Hembra\");\n\n&nbsp; &nbsp; &nbsp; console.log(francisco.nombre);\n&nbsp; &nbsp; &nbsp; console.log(beatriz.nombre);\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Si vamos a necesitar varias <strong>instancias<\/strong> del mismo tipo que estemos creando, en vez de crear <strong>varias<\/strong> funciones con el mismo c\u00f3digo repetido, lo que conviene m\u00e1s es hacer una <strong>funci\u00f3n constructora<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Por lo que podemos ver, la funci\u00f3n <em>hablar()<\/em> la podemos en vez de cargarla en todas las <strong>instancias<\/strong>, cargarla solo de manera \u00fanica cuando la necesitemos. Lo suyo ser\u00eda asignar al <strong>prototipo<\/strong> de la funci\u00f3n <em>Persona()<\/em> el m\u00e9todo <em>hablar()<\/em>, es decir, sacarlo de la <strong>funci\u00f3n protot\u00edpica<\/strong> y asociarlo a la misma fuera de ella, ya que al tenerlo dentro de la misma, cada vez que generamos una <strong>instancia<\/strong> de nuestra <strong>funci\u00f3n protot\u00edpica<\/strong>, se est\u00e1 duplicando este m\u00e9todo <em>hablar()<\/em>, y si tuvi\u00e9ramos m\u00e1s <strong>m\u00e9todos<\/strong>, se estar\u00edan duplicando en todas las <strong>instancias<\/strong>, consumiendo memoria. Lo ideal es que nuestras <strong>funciones constructoras<\/strong> s\u00f3lo tengan los <strong>atributos<\/strong>, y los <strong>m\u00e9todos<\/strong> los saquemos de nuestra <strong>funci\u00f3n constructora<\/strong> y se los peguemos al <strong>prototipo<\/strong> de la siguiente forma.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"es\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Prototipos en Javascript&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Prototipos en Javascript&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; function Persona(nombre, genero) {\n&nbsp; &nbsp; &nbsp; &nbsp; this.nombre = nombre;\n&nbsp; &nbsp; &nbsp; &nbsp; this.genero = genero;\n&nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; \/\/ M\u00e9todos agregados al prototipo de la funci\u00f3n constructora\n&nbsp; &nbsp; &nbsp; Persona.prototype.hablar = function () {\n&nbsp; &nbsp; &nbsp; &nbsp; console.log(`Hola, mi nombre es ${this.nombre}`);\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; const francisco = new Persona(\"Francisco\", \"Macho\");\n&nbsp; &nbsp; &nbsp; console.log(francisco);\n&nbsp; &nbsp; &nbsp; francisco.hablar();\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>En este cap\u00edtulo comenzaremos a hablar sobre una de las cosas m\u00e1s importantes en Javascript, y son los prototipos. Javascript es un&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":685,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","footnotes":""},"class_list":["post-687","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"En este cap\u00edtulo comenzaremos a hablar sobre una de las cosas m\u00e1s importantes en Javascript, y son los prototipos. Javascript es un...","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/687","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=687"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/687\/revisions"}],"predecessor-version":[{"id":689,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/687\/revisions\/689"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/685"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=687"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}