{"id":655,"date":"2024-07-30T19:48:49","date_gmt":"2024-07-30T17:48:49","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=655"},"modified":"2024-07-30T19:48:50","modified_gmt":"2024-07-30T17:48:50","slug":"010-objetos-en-javascript","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/03-tipos-de-datos-en-javascript\/010-objetos-en-javascript\/","title":{"rendered":"010. Objetos en Javascript"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Los <strong>objetos<\/strong> son una parte muy importante de <strong>Javascript<\/strong>. Hay una frase entre los desarrolladores <strong>Javascript<\/strong> de que <strong><em>En Javascript todo es un objeto<\/em>. <\/strong>A d\u00eda de hoy tenemos <strong>bases de datos<\/strong> basadas en notaci\u00f3n de objetos <strong>javascript<\/strong>, como <strong>Firebase<\/strong>, <strong>MongoDB<\/strong>&#8230; que son bases de datos muy poderosas y utilizadas actualmente.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h2 class=\"wp-block-heading\">Crear un objeto<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">La sintaxis es la siguiente.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const a = {};\nconsole.log(a);\n\n\/\/ No es recomendado\nconst b = new Object();\nconsole.log(b);<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Qu\u00e9 es un objeto<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Un <strong>objeto<\/strong> es una colecci\u00f3n de <strong>llaves: valores<\/strong>. Si hemos trabajado con <strong>CSS<\/strong>, es parecido a una <strong>regla CSS<\/strong>, hay que definir una <strong>llave<\/strong>, dos puntos, y el valor que asignemos a la <strong>llave<\/strong> de un <strong>objeto<\/strong>, separado por comas. Un <strong>objeto<\/strong> puede tener diferentes <strong>propiedades<\/strong> o <strong>valores<\/strong>, y se pueden pasar <strong>funciones<\/strong> como datos.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const fran = {\n   nombre: \"Francisco\",\n   apellido: \"Paredes\",\n   edad: 51\n   pasatiempos: [\"Correr\", \"Ejercicio\"],\n   soltero: false,\n   contacto: {\n      email: \"francisco@franciscoparedesparralejo.eu\",\n      twitter: \"@franwebsite\"\n   },\n   saludar: function(){\n      console.log(\"Hola\");\n   }\n};\n\nconsole.log(fran);<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Acceder a los valores del objeto<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Cuando en su momento hablamos de los tipos de datos compuestos, dijimos que no acced\u00edamos al valor directamente, sino a la referencia del mismo. Mientras que en los <strong>arrays<\/strong> utiliz\u00e1bamos la <strong>notaci\u00f3n del corchete<\/strong> para acceder a los valores, con los <strong>objetos<\/strong> utilizamos la notaci\u00f3n del punto (.), aunque tambi\u00e9n se podr\u00eda utilizar la notaci\u00f3n del corchete, pero no es lo habitual.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">console.log(fran.nombre); \/\/ Forma m\u00e1s aceptada\nconsole.log(fran[\"nombre\"]; \/\/ No se suele utilizar esta sintaxis\nfran.saludar();\nconsole.log(fran.pasatiempos[1]);\nconsole.log(fran.contacto.twitter);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">En los <strong>objetos<\/strong>, las <strong>propiedades<\/strong> son denominadas <strong>atributos<\/strong>, que no son m\u00e1s que <strong>variables<\/strong> que tienen dentro un <strong>objeto<\/strong>. Las <strong>funciones<\/strong> dentro de los objetos son denominadas <strong>m\u00e9todos<\/strong>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Nota<\/strong>: Dentro de un objeto a las <strong>variables<\/strong> se las llaman <strong>atributos<\/strong>, y a las <strong>funciones<\/strong> se las denomina <strong>m\u00e9todos<\/strong>.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">En nuestro objeto <em>fran<\/em> vamos a crear otra <strong>funci\u00f3n<\/strong> con la siguiente sintaxis.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; decirMiNombre: function(){\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Hola, me llamo ${this.nombre} ${this.apellido}\n                y me puedes seguir como ${this.contacto.twitter}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">La palabra <strong><em>this<\/em> <\/strong>hace referencia al mismo objeto.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusi\u00f3n<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Como podemos ver, los <strong>objetos<\/strong> pueden tener cualquier valor, sean <strong>cadenas<\/strong>, <strong>n\u00fameros<\/strong>, <strong>arrays,<\/strong> <strong>funciones<\/strong>, otros <strong>objetos<\/strong>, <strong>booleans<\/strong>&#8230; pr\u00e1cticamente cualquier tipo de dato de los que hemos visto. M\u00e1s adelante, cuando lleguemos a la parte de <strong>paradigmas de programaci\u00f3n<\/strong>, y hablemos de <strong>programaci\u00f3n orientada a objetos<\/strong>, ah\u00ed vamos a entender porque en <strong>Javascript<\/strong> los <strong>objetos<\/strong> lo son todo.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">M\u00e9todos importantes de los objetos<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Algunos <strong>m\u00e9todos<\/strong> importantes son:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>keys(objeto)<\/em><\/strong>: recibe como par\u00e1metro un <strong>objeto<\/strong>, es un <strong>m\u00e9todo<\/strong> que tiene el prototipo <strong><em>object<\/em><\/strong>, y que permite listar todas las <strong>llaves<\/strong> del <strong>objeto<\/strong>.<\/li>\n\n\n\n<li><strong><em>values(objeto)<\/em><\/strong>: forma un <strong>array<\/strong> con los valores del objeto que le pasamos como <strong>par\u00e1metro<\/strong>.<\/li>\n\n\n\n<li><strong><em>objeto.hasOwnProperty(\u00abpropiedad\u00bb)<\/em><\/strong>: este <strong>m\u00e9todo<\/strong> permite saber si un <strong>objeto<\/strong> tiene una <strong>propiedad<\/strong>. Devolver\u00e1 true o false dependiendo de si existe o no dicha propiedad pasada como par\u00e1metro. Primero se pone el <strong>objeto<\/strong> en cuesti\u00f3n, el <strong>m\u00e9todo<\/strong>, y como par\u00e1metro el nombre de la <strong>propiedad<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Los objetos tienen muchas propiedades, las cuales podemos encontrar en <a href=\"https:\/\/developer.mozilla.org\/es\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>MDN<\/strong><\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Ejm completo<\/h2>\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&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;Objetos Javascript&lt;\/title&gt;\n&lt;\/head&gt;\n\n&lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Objetos Javascript&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; &nbsp; const fran = {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nombre: \"Francisco\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; apellido: \"Paredes\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; edad: 51,\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; soltero: false,\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pasatiempos: [\"Correr\",\"Tocar el bajo\"],\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contacto: {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; email: \"francisco@franciscoparedesparralejo.eu\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; twitter: \"@franwebsite\"\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; saludar: function(){\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Hola\");\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; decirMiNombre: function(){\n\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Hola, me llamo ${this.nombre} ${this.apellido}\n                y me puedes seguir como ${this.contacto.twitter} en Twitter`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; &nbsp; };\n&nbsp; &nbsp; &nbsp; &nbsp; fran.decirMiNombre();\n&nbsp; &nbsp; &lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Los objetos son una parte muy importante de Javascript. Hay una frase entre los desarrolladores Javascript de que En Javascript todo es&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":628,"menu_order":9,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","footnotes":""},"class_list":["post-655","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":"Los objetos son una parte muy importante de Javascript. Hay una frase entre los desarrolladores Javascript de que En Javascript todo es...","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/655","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=655"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/655\/revisions"}],"predecessor-version":[{"id":657,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/655\/revisions\/657"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/628"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=655"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}