diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:46:50 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:46:50 +0100 |
commit | a55b575e8089ee6cab7c5c262a7e6db55d0e34d6 (patch) | |
tree | 5032e6779a402a863654c9d65965073f09ea4182 /files/es/web/javascript/reference/global_objects/object | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.tar.gz translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.tar.bz2 translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.zip |
unslug es: move
Diffstat (limited to 'files/es/web/javascript/reference/global_objects/object')
33 files changed, 5577 insertions, 0 deletions
diff --git a/files/es/web/javascript/reference/global_objects/object/__definegetter__/index.html b/files/es/web/javascript/reference/global_objects/object/__definegetter__/index.html new file mode 100644 index 0000000000..fceb708912 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/__definegetter__/index.html @@ -0,0 +1,144 @@ +--- +title: Object.prototype.__defineGetter__() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/__defineGetter__ +tags: + - JavaScript + - Objeto + - Prototipo + - Prototype + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ +--- +<div>{{JSRef}}</div> + +<div class="warning"> +<p>Esta característica está obsoleta en favor de definir getters usando el <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer syntax</a> o la API {{jsxref("Object.defineProperty()")}}.</p> + +<p>En todo caso, como es ampliamente implementada y usada en la Web, es poco probable que los navegadores dejen de implementarla.</p> +</div> + +<p>El método <code><strong>__defineGetter__</strong></code> enlaza una propiedad de un objeto a una función a ser llamada cuando esa propiedad es buscada.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code><var>obj</var>.__defineGetter__(<var>prop</var>, <var>func</var>)</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>Un texto (string) que contiene el nombre de la propiedad para enlazar la función dada.</dd> + <dt><code>func</code></dt> + <dd>A function to be bound to a lookup of the specified property.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>The <code>__defineGetter__</code> allows a {{jsxref("Operators/get", "getter", "", 1)}} to be defined on a pre-existing object.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">// Forma no-estándar y obsoleta + +var o = {}; +o.__defineGetter__('gimmeFive', function() { return 5; }); +console.log(o.gimmeFive); // 5 + + +// Formas compatibles con el estándar + +// Usando el operador get +var o = { get gimmeFive() { return 5; } }; +console.log(o.gimmeFive); // 5 + +// Usando Object.defineProperty +var o = {}; +Object.defineProperty(o, 'gimmeFive', { + get: function() { + return 5; + } +}); +console.log(o.gimmeFive); // 5 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('JavaScript', '#object.prototype.__definegetter__', 'Object.prototype.__defineGetter__()')}}</td> + <td>{{Spec2('JavaScript')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("11")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>{{jsxref("Object.prototype.__defineSetter__()")}}</li> + <li>{{jsxref("Operators/get", "get")}} operator</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.prototype.__lookupGetter__()")}}</li> + <li>{{jsxref("Object.prototype.__lookupSetter__()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">JS Guide: Defining Getters and Setters</a></li> + <li><a href="http://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/">[Blog Post] Deprecation of __defineGetter__ and __defineSetter__</a></li> + <li>{{bug(647423)}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html b/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html new file mode 100644 index 0000000000..8292222a38 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html @@ -0,0 +1,84 @@ +--- +title: Object.prototype.__lookupGetter__() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/__lookupGetter__ +translation_of: Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p>Los <code><strong>__lookupGetter__</strong></code> metodos retornan la funcion enlazada como un getter para especificar la propiedad.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>obj</var>.__lookupGetter__(<var>sprop</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>sprop</code></dt> + <dd>A string containing the name of the property whose getter should be returned.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>The function bound as a getter to the specified property.</p> + +<h2 id="Description">Description</h2> + +<p>If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. <code>__lookupGetter__</code> can be used to obtain a reference to the getter function.</p> + +<p>It is now possible to do this in a standardized way using {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.getPrototypeOf()")}}.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">var obj = { + get foo() { + return Math.random() > 0.5 ? 'foo' : 'bar'; + } +}; + + +// Non-standard and deprecated way +obj.__lookupGetter__('foo'); +// (function() { return Math.random() > 0.5 ? 'foo' : 'bar'; }) + + +// Standard-compliant way +Object.getOwnPropertyDescriptor(obj, "foo").get; +// (function() { return Math.random() > 0.5 ? 'foo' : 'bar'; }) +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.__lookupGetter__', 'Object.prototype.__lookupGetter__()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.lookupGetter")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.__lookupSetter__()")}}</li> + <li>{{jsxref("Functions/get", "get")}} operator</li> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.getPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.__defineGetter__()")}}</li> + <li>{{jsxref("Object.prototype.__defineSetter__()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">JS Guide: Defining Getters and Setters</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/assign/index.html b/files/es/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..17de417d75 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,274 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/assign +tags: + - ECMAScript 2015 + - JavaScript + - Objeto + - Referencia + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +<div>{{JSRef}}</div> + +<p>El método <strong><code>Object.assign()</code></strong> copia todas las propiedades enumerables de uno o más objetos fuente a un objeto destino. Devuelve el objeto destino. </p> + +<div>{{EmbedInteractiveExample("pages/js/object-assign.html")}}</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">Object.assign(<var>objetivo</var>, ...<var>fuentes</var>)</pre> + +<h3 id="Parámetros" name="Parámetros">Parámetros</h3> + +<dl> + <dt><code>objetivo</code></dt> + <dd>El objeto destino.</dd> + <dt><code>fuentes</code></dt> + <dd>Los objetos origen.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>El objeto destino.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>Las propiedades en el objeto destino serán sobrescritas por las propiedades en las fuentes si tienen la misma clave. Propiedades posteriores de las fuentes podrán sobrescribir las anteriores.</p> + +<p>El método <code>Object.assign()</code> copia sólo las propiedades <em>enumerables</em> y <em>propias</em> del objeto origen a un objeto destino. Usa <code>[[Get]]</code> en la origen y <code>[[Set]] </code>en el destino, por lo que invocará los métodos de acceso y establecimiento (<em>getters</em> y <em>setters</em>). Por consiguiente <em>asignará</em> propiedades frente a sólo copiar o definir propiedades nuevas. Esto puede hacer que sea inadecuado para fusionar propiedades nuevas en un prototipo si los objetos fuente contienen métodos de acceso (<em>getters</em>). Para copiar definiciones de propiedades en prototipos, incluyendo su enumerabilidad, se deben usar {{jsxref("Object.getOwnPropertyDescriptor()")}} y {{jsxref("Object.defineProperty()")}}.</p> + +<p>Tanto las propiedades {{jsxref("String")}} como {{jsxref("Symbol")}} son copiadas.</p> + +<p>En caso de un error, por ejemplo si una propiedad es de solo lectura, se lanza un {{jsxref("TypeError")}}, y el objeto destino se mantendrá sin cambios.</p> + +<p>Note que <code>Object.assign()</code> no lanza excepciones al encontrar en las fuentes propiedades {{jsxref("null")}} o {{jsxref("undefined")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Clonando_un_objeto">Clonando un objeto</h3> + +<pre class="brush: js">var obj = { a: 1 }; +var copy = Object.assign({}, obj); +console.log(copy); // { a: 1 } +</pre> + +<h3 id="Advertencia_para_clonado_profundo">Advertencia para clonado profundo</h3> + +<p>Para un clonado profundo, necesitamos usar otra alternativa ya que <code>Object.assign()</code> copia valores de propiedades. Si el valor en la fuente es una referencia a un objeto, solo se copia la referencia en sí, como valor de la propiedad.</p> + +<pre class="brush: js">function test() { + 'use strict'; + + let obj1 = { a: 0 , b: { c: 0}}; + let obj2 = Object.assign({}, obj1); + console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}} + + obj1.a = 1; + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}} + console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}} + + obj2.a = 2; + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}} + console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}} + + obj2.b.c = 3; + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}} + console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}} + + // Deep Clone + obj1 = { a: 0 , b: { c: 0}}; + let obj3 = JSON.parse(JSON.stringify(obj1)); + obj1.a = 4; + obj1.b.c = 4; + console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}} +} + +test();</pre> + +<h3 id="Fusionando_objetos">Fusionando objetos</h3> + +<pre class="brush: js">var o1 = { a: 1 }; +var o2 = { b: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign(o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 } +console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.</pre> + +<h3 id="Fusionando_objetos_con_las_mismas_propiedades">Fusionando objetos con las mismas propiedades</h3> + +<pre class="brush: js">var o1 = { a: 1, b: 1, c: 1 }; +var o2 = { b: 2, c: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign({}, o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 }</pre> + +<p>Las propiedades también son sobreescritas por otros objetos que aparecen posteriormente en la lista de parámetros y que tienen propiedades con el mismo nombre.</p> + +<h3 id="Copiando_propiedades_de_tipo_símbolo">Copiando propiedades de tipo símbolo</h3> + +<pre class="brush: js">var o1 = { a: 1 }; +var o2 = { [Symbol('foo')]: 2 }; + +var obj = Object.assign({}, o1, o2); +console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox) +Object.getOwnPropertySymbols(obj); // [Symbol(foo)] +</pre> + +<h3 id="Las_propiedades_heredadas_y_las_no_enumerables_no_pueden_ser_copiadas">Las propiedades heredadas y las no enumerables no pueden ser copiadas</h3> + +<pre class="brush: js">var obj = Object.create({ foo: 1 }, { // foo es una propiedad heredada. + bar: { + value: 2 // bar es una propiedad no enumerable. + }, + baz: { + value: 3, + enumerable: true // baz es una propiedad propia enumerable. + } +}); + +var copy = Object.assign({}, obj); +console.log(copy); // { baz: 3 } +</pre> + +<h3 id="Los_tipos_primitivos_serán_encapsulados_en_objetos">Los tipos primitivos serán encapsulados en objetos</h3> + +<pre class="brush: js">var v1 = 'abc'; +var v2 = true; +var v3 = 10; +var v4 = Symbol('foo') + +var obj = Object.assign({}, v1, null, v2, undefined, v3, v4); +// Los tipos primitivos son encapsulados en objetos y se ignoran las propiedades con valor null o undefined. +// Nótese que sólo los wrappers de cadenas tienen propiedades enumerables: +console.log(obj); // { "0": "a", "1": "b", "2": "c" } +</pre> + +<h3 id="Las_excepciones_interrumpen_la_tarea_de_copiado">Las excepciones interrumpen la tarea de copiado</h3> + +<pre class="brush: js">var target = Object.defineProperty({}, 'foo', { + value: 1, + writeable: false +}); // target.foo es una propiedad de sólo lectura + +Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); +// TypeError: "foo" es de sólo lectura +// La excepción se lanza cuando se intenta asignar un valor a target.foo + +console.log(target.bar); // 2, la primera fuente fue copiada. +console.log(target.foo2); // 3, la primera propiedad del segundo objeto fuente se copió correctamente. +console.log(target.foo); // 1, se lanza la excepción. +console.log(target.foo3); // undefined, el método assign ha finalizado, no se copiará foo3. +console.log(target.baz); // undefined, tampoco se copiará el tercer objecto fuente. +</pre> + +<h3 id="Copiando_métodos_de_acceso">Copiando métodos de acceso</h3> + +<pre class="brush: js">var obj = { + foo: 1, + get bar() { + return 2; + } +}; + +var copy = Object.assign({}, obj); +console.log(copy); +// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value. + +// This is an assign function that copies full descriptors +function completeAssign(target, ...sources) { + sources.forEach(source => { + let descriptors = Object.keys(source).reduce((descriptors, key) => { + descriptors[key] = Object.getOwnPropertyDescriptor(source, key); + return descriptors; + }, {}); + // by default, Object.assign copies enumerable Symbols too + Object.getOwnPropertySymbols(source).forEach(sym => { + let descriptor = Object.getOwnPropertyDescriptor(source, sym); + if (descriptor.enumerable) { + descriptors[sym] = descriptor; + } + }); + Object.defineProperties(target, descriptors); + }); + return target; +} + +var copy = completeAssign({}, obj); +console.log(copy); +// { foo:1, get bar() { return 2 } } +</pre> + +<h2 id="Polyfill" name="Polyfill">Polyfill</h2> + +<p>Este {{Glossary("Polyfill","polyfill")}} no soporta propiedades símbolo, ya que ES5 no tiene símbolos.</p> + +<pre class="brush: js">if (typeof Object.assign != 'function') { + // Must be writable: true, enumerable: false, configurable: true + Object.defineProperty(Object, "assign", { + value: function assign(target, varArgs) { // .length of function is 2 + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }, + writable: true, + configurable: true + }); +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div> +<p>{{Compat("javascript.builtins.Object.assign")}}</p> +</div> + +<h2 id="Ver_también" name="Ver también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li><a href="/es/docs/Web/JavaScript/enumeracion_y_propietario_de_propiedades">Enumeración y propietarios de propiedades</a></li> + <li><a href="https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/Sintaxis_Spread#Spread_en_literales_tipo_Objeto">Spread en literales tipo Objeto</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/constructor/index.html b/files/es/web/javascript/reference/global_objects/object/constructor/index.html new file mode 100644 index 0000000000..3871c41fe3 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/constructor/index.html @@ -0,0 +1,161 @@ +--- +title: Object.prototype.constructor +slug: Web/JavaScript/Referencia/Objetos_globales/Object/constructor +tags: + - JavaScript + - Object + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/constructor +--- +<div>{{JSRef("Objetos_globales", "Object")}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>Retorna una referencia a la función del {{jsxref("Object")}} que creó el objeto de la instancia. Note que el valor de esta propiedad es una referencia a la función misma, no a un string conteniendo el nombre de la función. El valor es sólo de lectura para valores primitivos tales como 1, true y 'test'.</p> + +<h2 id="Description" name="Description">Descripción</h2> + +<p>Todos los objetos tienen una propiedad <code>constructor.</code> Los objetos creados sin explicitar el uso de una función (como son los objetos y las cadenas literales) tendrán una propiedad de <code>constructor</code> que apunta al tipo de constructor del Objeto Fundamento para ese objeto.</p> + +<pre class="brush:js">var o = {}; +o.constructor === Object; // true + +var a = []; +a.constructor === Array; // true + +var n = new Number(3); +n.constructor === Number; // true</pre> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<h3 id="Example:_Displaying_the_constructor_of_an_object" name="Example:_Displaying_the_constructor_of_an_object">Ejemplo: Mostrando el constructor de un objeto.</h3> + +<p>El siguiente ejemplo crea un prototipo, <code>Tree</code>, y un objeto de este tipo, <code>theTree</code>. El ejemplo muestra entonces la propiedad <code>constructor</code> para el objeto <code>theTree</code>.</p> + +<pre class="brush:js">function Tree (name) { + this.name = name; +} + +var theTree = new Tree( "Redwood" ); +console.log( "theTree.constructor is " + theTree.constructor );</pre> + +<p>Este ejemplo muestra la siguiente salida:</p> + +<pre class="brush:js">theTree.constructor is function Tree (name) { + this.name = name; +}</pre> + +<h3 id="Example:_Changing_the_constructor_of_an_object" name="Example:_Changing_the_constructor_of_an_object">Ejemplo: Cambiando el constructor de un objeto.</h3> + +<p>El siguiente ejemplo demuestra como modificar el valor del constructor de objetos genéricos. Solo <code>true</code>, <code>1</code> y <code>"test"</code> no serán afectados ya que ellos tienen constructores nativos de solo lectura. Este ejemplo demuestra que no siempre es seguro confiar en la propiedad constructor de un objeto.</p> + +<pre class="brush:js">function Type () {} + +var types = [ + new Array(), + [], + new Boolean(), + true, // no cambia +<span style="line-height: normal;"> </span>new Date(), +<span style="line-height: normal;"> </span>new Error(), +<span style="line-height: normal;"> </span>new Function(), + function () {}, +<span style="line-height: normal;"> </span>Math, +<span style="line-height: normal;"> </span>new Number(), + 1, // no cambia +<span style="line-height: normal;"> </span>new Object(), + {}, +<span style="line-height: normal;"> </span>new RegExp(), + /(?:)/, +<span style="line-height: normal;"> </span>new String(), + "test" // no cambia +]; + +for( var i = 0; i < types.length; i++ ) { + types[i].constructor = Type; + types[i] = [ types[i].constructor, types[i] instanceof Type, types[i].toString() ]; +} + +console.log( types.join( "\n" ) );</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>ECMAScript 1ra. Edición. Implementado en JavaScript 1.1</td> + <td>Estandar.</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.1', 'Objectprototype.constructor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> diff --git a/files/es/web/javascript/reference/global_objects/object/create/index.html b/files/es/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..94608d1c58 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,377 @@ +--- +title: Object.create() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/create +tags: + - ECMAScript5 + - JavaScript + - 'Null' + - Objeto + - Referencia + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.create()</strong></code> crea un objeto nuevo, utilizando un objeto existente como el prototipo del nuevo objeto creado.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-create.html")}}</div> + +<div></div> + +<div>La fuente de este ejemplo interactivo se almacena en un repositorio de GitHub. Si desea contribuir al proyecto de ejemplos interactivos, clone https://github.com/mdn/interactive-examples y envíenos una solicitud de extracción (pull request).</div> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">Object.create(<var>proto</var>[, <var>propertiesObject</var>])</pre> + +<h3 id="Parámetros" name="Parámetros">Parámetros</h3> + +<dl> + <dt><em>proto</em></dt> + <dd>Objeto el cual debe ser el prototipo del nuevo objeto creado.</dd> + <dt><em>propertiesObject</em></dt> + <dd>Opcional. Si se especifica y no es {{jsxref("undefined")}}, un objeto cuyas propiedades enumerables propias (es decir, aquellas propiedades definidas sobre si mismo y <em>no</em> son propiedades enumerable a lo largo de su cadena de prototipos) espefica descriptores de propiedad para ser agregadas al objeto recien creado, con los nombres de propiedad correspondiente. Estas propiedades corresponden al segundo argumento de {{jsxref("Object.defineProperties")}}.</dd> +</dl> + +<h3 id="Description" name="Description">Valor devuelto</h3> + +<p>Un nuevo objeto con el prototipo y propiedades del objeto especificado.</p> + +<h3 id="Excepciones">Excepciones</h3> + +<p>Una excepción {{jsxref("TypeError")}} si el parámetro <code>propertiesObject</code> es {{jsxref("null")}} o un objeto envolvente no primitivo.</p> + +<h2 id="Ejemplos" name="Ejemplos">Ejemplos</h2> + +<h3 id="Herencia_clásica_con_Object.create">Herencia clásica con <code>Object.create()</code></h3> + +<p>Debajo se encuentra un ejemplo de cómo usar <code>Object.create()</code> para lograr herencia clásica. Este es para herencia simple, la cual es todo lo que soporta JavaScript.</p> + +<pre class="brush: js notranslate">// Shape - superclase +function Shape() { + this.x = 0; + this.y = 0; +} + +// método de la superclase +Shape.prototype.move = function(x, y) { + this.x += x; + this.y += y; + console.info("Shape moved."); +}; + +// Rectangle - subclase +function Rectangle() { + Shape.call(this); // llama al contructor de la superclase. +} + +// subclase extiende superclase +Rectangle.prototype = Object.create(Shape.prototype); +Rectangle.prototype.constructor = Rectangle; + +var rect = new Rectangle(); + +console.log('¿Es rect una instancia de Rectangle?', + rect instanceof Rectangle); // true +console.log('¿Es rect una instancia de Shape?', + rect instanceof Shape); // true +rect.move(1, 1); // Imprime, 'Shape moved.' +</pre> + +<p>Si desea heredar desde múltiples objetos, entonces los mixins son una posibilidad.</p> + +<pre class="brush: js notranslate">function MyClass() { + SuperClass.call(this); + OtherSuperClass.call(this); +} + +// inherit one class +MyClass.prototype = Object.create(SuperClass.prototype); +// mixin another +Object.assign(MyClass.prototype, OtherSuperClass.prototype); +// re-assign constructor +MyClass.prototype.constructor = MyClass; + +MyClass.prototype.myMethod = function() { + // do something +}; +</pre> + +<p>{{jsxref("Object.assign()")}} copia las propiedades del prototipo <em>OtherSuperClass</em> al prototipo de <em>MyClass</em>, haciéndolas disponibles en todas las instancias de <em>MyClass</em>. <code>Object.assign()</code> se introdujo con ES2015 y <a href="/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign#Polyfill">tiene polyfill</a>. Si el soporte para navegadores antiguos es necesario, se puede utilizar <code><a href="https://api.jquery.com/jQuery.extend/">jQuery.extend()</a></code> o <code><a href="https://lodash.com/docs/#assign">_.assign()</a></code>.</p> + +<h3 id="Usando_el_argumento_propertiesObject_con_Object.create">Usando el argumento <code>propertiesObject</code> con <code>Object.create()</code></h3> + +<pre class="brush: js notranslate">var o; + +// crea un objeto con un prototipo como null +o = Object.create(null); + + +o = {}; +// esto equivale a: +o = Object.create(Object.prototype); + + +// Ejemplo en donde creamos un objeto con un par de propiedades de ejemplo. +// (Note que el segundo parámetro mapea claves para los *descriptores de propiedad*.) +o = Object.create(Object.prototype, { + // foo es un habitual "propiedad de valor" + foo: { writable:true, configurable:true, value: "hello" }, + // bar es una propiedad getter-and-setter (de acceso) + bar: { + configurable: false, + get: function() { return 10 }, + set: function(value) { console.log("Setting `o.bar` to", value) } +}}); + + +function Constructor(){} +o = new Constructor(); +// es equivalente a: +o = Object.create(Constructor.prototype); +// Por supuesto, si hay un código de inicialización en la +// función Constructor, el Object.create no puede reflejar esta. + + +// crear un nuevo objeto cuyo prototipo es un nuevo, objeto vacío +// y agregar una única propiedad 'p', con el valor 42 +o = Object.create({}, { p: { value: 42 } }) + +// por defecto las propiedades NO SON editables, enumerables o configurables: +o.p = 24 +o.p +// 42 + +o.q = 12 +for (var prop in o) { + console.log(prop) +} +// "q" + +delete o.p +// false + +// <span style="font-size: 1rem;">para especificar una propiedad en ES3</span> + +o2 = Object.create({}, { p: { + value: 42, + writable: true, + enumerable: true, + configurable: true } +}); +</pre> + +<h2 id="Objetos_personalizados_y_nulos">Objetos personalizados y nulos</h2> + +<p>Un objeto nuevo creado de un objeto completamente personalizado (especialmente uno creado de un objeto nulo, que es básicamente un objeto personalizado sin miembros) puede comportarse de manera inesperada. Esto es especialmente cierto cuando se depura, ya que las funciones comunes de conversión/detección de propiedad de objeto pueden generar errores, o simplemente perder información (especialmente si se atrapan excepciones de manera silenciosa que ignoran los errores). Por ejemplo, aquí hay dos objetos:</p> + +<pre class="brush: js notranslate">oco = Object.create( {} ); // Crea un objeto normal +ocn = Object.create( null ); // Crea un objeto "null" + +> console.log(oco) // {} -- Parece normal +> console.log(ocn) // {} -- Parece normal aquí también, hasta este momento + +oco.p = 1; // Crea una propiedad simple en un objeto normal +ocn.p = 0; // Crea una propiedad simple en un objeto "null" + +> console.log(oco) // {p: 1} -- Todavía parece normal +> console.log(ocn) // {p: 0} --Todavía parece normal aquí también. PERO ESPERA... +</pre> + +<p>Como se muestra arriba, todo parece normal hasta ahora. Sin embargo, al intentar usar estos objetos, sus diferencias se hacen evidentes rápidamente:</p> + +<pre class="brush: js notranslate">> "oco is: " + oco // Muestra "ocn is: [object Object]" + +> "ocn is: " + ocn // Arroja error: Cannot convert object to primitive value +</pre> + +<p>Probar solo algunas de las funciones incorporadas más básicas muestra la magnitud del problema más claramente:</p> + +<pre class="brush: js notranslate">> alert(oco) // Muestra: [object Object] +> alert(ocn) // Arroja error: Cannot convert object to primitive value + +> oco.toString() // Muestra [object Object] +> ocn.toString() // Arroja error: ocn.toString is not a function + +> oco.valueOf() // Muestra{} +> ocn.valueOf() // Arroja error: ocn.valueOf is not a function + +> oco.hasOwnProperty("p") // Muestra "true" +> ocn.hasOwnProperty("p") // Arroja error: ocn.hasOwnProperty is not a function + +> oco.constructor // Muestra "Object() { [native code] }" +> ocn.constructor // Muestra "undefined" +</pre> + +<p>Como se dijo, estas diferencias pueden hacer que la depuración e incluso problemas aparentemente simples se pierdan rápidamente. Por ejemplo:</p> + +<p><em>Una función simple de depuración:</em></p> + +<pre class="brush: js notranslate">// mostrar nombre de propiedad de nivel superior: pares de valores de un objeto dado +function ShowProperties( b ){ + for( var i in b ){ console.log( i + ": " + b[i] + "\n" ) } +}</pre> + +<p><em>Resultados no tan simples: (especialmente si la captura silenciosa de errores había ocultado los mensajes de error)</em></p> + +<pre class="brush: js notranslate">ob={}; ob.po=oco; ob.pn=ocn; // crear un objeto compuesto usando los objetos de prueba de arriba como valores de propiedad + +> ShowProperties( ob ) // Muestra propiedades de nivel superior +- po: [object Object] +- Error: Cannot convert object to primitive value + +Tenga en cuenta que solo se muestra la primera propiedad. +</pre> + +<p><em>(Pero si se crea el mismo objeto simplemente en un orden diferente, al menos en algunas implementaciones ...)</em></p> + +<pre class="brush: js notranslate">ob={}; ob.pn=ocn; ob.po=oco; // cree el mismo objeto compuesto nuevamente, pero cree las mismas propiedades en un orden diferente + +> ShowProperties( ob ) // Muestra propiedades de nivel superior +- Error: Cannot convert object to primitive value + +Tenga en cuenta que ninguna propiedad se muestra.</pre> + +<p>Tenga en cuenta que un orden tan diferente puede surgir estáticamente a través de codificaciones fijas dispares, como aquí, pero también dinámicamente a través del orden en que se ejecutan dichas ramas de código de adición de propiedades en tiempo de ejecución, ya que depende de entradas y / o variables aleatorias. Por otra parte, el orden de iteración real no está garantizado, independientemente de cómo son agregados los miembros.</p> + +<h4 id="Algunas_NO-soluciones">Algunas NO-soluciones</h4> + +<p>A good solution for the missing object-methods is not immediately apparent.</p> + +<p>Adding the missing object-method directly from the standard-object does NOT work:</p> + +<pre class="brush: js notranslate">ocn = Object.create( null ); // create "null" object (same as before) + +ocn.toString = Object.toString; // since new object lacks method then try assigning it directly from standard-object + +<span style="">> ocn.toString // shows "toString() { [native code] }" -- missing method seems to be there now</span> +> ocn.toString == Object.toString // shows "true" -- method seems to be same as the standard object-method + +> ocn.toString() // error: Function.prototype.toString requires that 'this' be a Function +</pre> + +<p><br> + Adding the missing object-method directly to new object's "prototype" does not work either, since new object does not have a real prototype (which is really the cause of ALL these problems) and one cannot be <strong>directly</strong> added:</p> + +<pre class="brush: js notranslate">ocn = Object.create( null ); // create "null" object (same as before) + +ocn.prototype.toString = Object.toString; // Error: Cannot set property 'toString' of undefined + +ocn.prototype = {}; // try to create a prototype +ocn.prototype.toString = Object.toString; // since new object lacks method then try assigning it from standard-object <span style=""> + +> ocn.toString() // error: ocn.toString is not a function</span> +</pre> + +<p><br> + Adding the missing object-method by using the standard-object<strong> </strong>as new object's prototype does not work either:</p> + +<pre class="brush: js notranslate">ocn = Object.create( null ); // create "null" object (same as before) +Object.setPrototypeOf(ocn, Object); // set new object's prototype to the standard-object + +> ocn.toString() // error: Function.prototype.toString requires that 'this' be a Function +</pre> + +<h4 id="Algunas_soluciones_aceptables">Algunas soluciones aceptables</h4> + +<p>Again, adding the missing object-method directly from the <strong>standard-object </strong>does NOT work. However, adding the <strong>generic</strong> method directly, DOES:</p> + +<pre class="brush: js notranslate">ocn = Object.create( null ); // create "null" object (same as before) + +ocn.toString = toString; // since new object lacks method then assign it directly from generic version + +> ocn.toString() // shows "[object Object]" +> "ocn is: " + ocn // shows "ocn is: [object Object]" + + +ob={}; ob.pn=ocn; ob.po=oco; // create a compound object (same as before) + +> ShowProperties(ob) // display top-level properties +- po: [object Object] +- pn: [object Object] +</pre> + +<p>However, setting the generic <strong>prototype</strong> as the new object's prototype works even better:</p> + +<pre class="brush: js notranslate">ocn = Object.create( null ); // create "null" object (same as before) +Object.setPrototypeOf(ocn, Object.prototype); // set new object's prototype to the "generic" object (NOT standard-object) +</pre> + +<p><em>(In addition to all the string-related functions shown above, this also adds:)</em></p> + +<pre class="brush: js notranslate">> ocn.valueOf() // shows {} +> ocn.hasOwnProperty("x") // shows "false" +> ocn.constructor // shows "Object() { [native code] }" + +// ...and all the rest of the properties and methods of Object.prototype. +</pre> + +<p>As shown, objects modified this way now look very much like ordinary objects.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Este polyfill cubre el caso de uso principal el cual es la creación de un nuevo objeto para el prototipo que ha sido escogido pero no toma el segundo argumento en cuenta.</p> + +<p>Note that while the setting of <code>null</code> as <code>[[Prototype]]</code> is supported in the real ES5 <code>Object.create</code>, this polyfill cannot support it due to a limitation inherent in versions of ECMAScript lower than 5.</p> + +<pre class="brush: js notranslate"> if (typeof Object.create !== "function") { + Object.create = function (proto, propertiesObject) { + if (typeof proto !== 'object' && typeof proto !== 'function') { + throw new TypeError('Object prototype may only be an Object: ' + proto); + } else if (proto === null) { + throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument."); + } + + if (typeof propertiesObject != 'undefined') { + throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument."); + } + + function F() {} + F.prototype = proto; + + return new F(); + }; +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementado en JavaScript 1.8.5</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.create', 'Object.create')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{Compat("javascript.builtins.Object.create")}}</div> + +<h2 id="Ver_tambien" name="Ver_tambien">Ver también</h2> + +<ul> + <li>{{jsxref("Object.defineProperty")}}</li> + <li>{{jsxref("Object.defineProperties")}}</li> + <li>{{jsxref("Object.prototype.isPrototypeOf")}}</li> + <li>{{jsxref("Reflect.construct()")}}</li> + <li>Publicación de John Resig sobre <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/" title="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf()</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/es/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..3002dd200d --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,194 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/defineProperties +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Método(2) + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +<div>{{JSRef("Objetos_globales", "Object")}}</div> + +<h2 id="Summary" name="Summary">Sumario</h2> + +<p>El metodo <strong><code>Object.defineProperties()</code></strong> define nuevas o modifica propiedades existentes directamente en el objeto, retornando el objeto.</p> + +<h2 id="Syntax" name="Syntax">Sintáxis</h2> + +<pre class="syntaxbox"><code>Object.defineProperties(<em>obj</em>, <em>propiedades</em>)</code></pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt>obj</dt> + <dd>El objeto sobre el cual se crearán o modificaran sus propiedades.</dd> + <dt>propiedades</dt> + <dd>Un objeto cuyas propiedades enumerables propias consituyen descriptores para las propiedades a ser definidas o modificadas.</dd> +</dl> + +<h2 id="Description" name="Description">Descripción</h2> + +<p><code>Object.defineProperties</code>, en escencia, define todas las propiedades correspondientes a las propiedades propias con capacidad de enumeración de <code>props</code> en el objeto <code>objrops.</code></p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js">Object.defineProperties(obj, { + "property1": { + value: true, + writable: true + }, + "property2": { + value: "Hello", + writable: false + } + // etc. etc. +});</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Asumiendo una ejecución pristina del entorno con todos los nombres y propiedades referidas a sus valores iniciales, <code>Object.defineProperties</code> es casi completamente equivalente (note el comentario en <code>isCallable</code>) a la siguiente reimplementación de JavaScript:</p> + +<pre class="brush: js;highlight:[8]">function defineProperties(obj, properties) { + function convertToDescriptor(desc) { + function hasProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function isCallable(v) { + // NB: modify as necessary if other values than functions are callable. + return typeof v === "function"; + } + + if (typeof desc !== "object" || desc === null) + throw new TypeError("bad desc"); + + var d = {}; + + if (hasProperty(desc, "enumerable")) + d.enumerable = !!obj.enumerable; + if (hasProperty(desc, "configurable")) + d.configurable = !!obj.configurable; + if (hasProperty(desc, "value")) + d.value = obj.value; + if (hasProperty(desc, "writable")) + d.writable = !!desc.writable; + if ( hasProperty(desc, "get") ) { + var g = desc.get; + + if (!isCallable(g) && g !== "undefined") + throw new TypeError("bad get"); + d.get = g; + } + if ( hasProperty(desc, "set") ) { + var s = desc.set; + if (!isCallable(s) && s !== "undefined") + throw new TypeError("bad set"); + d.set = s; + } + + if (("get" in d || "set" in d) && ("value" in d || "writable" in d)) + throw new TypeError("identity-confused descriptor"); + + return d; + } + + if (typeof obj !== "object" || obj === null) + throw new TypeError("bad obj"); + + properties = Object(properties); + + var keys = Object.keys(properties); + var descs = []; + + for (var i = 0; i < keys.length; i++) + descs.push([keys[i], convertToDescriptor(properties[keys[i]])]); + + for (var i = 0; i < descs.length; i++) + Object.defineProperty(obj, descs[i][0], descs[i][1]); + + return obj; +}</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementada en JavaScript 1.8.5</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> + +<p>Basado en <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a>.</p> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>5 (previous versions untested)</td> + <td>9</td> + <td>11.60</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>11.50</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Ver también</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties" title="Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/es/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..f971d5a131 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,419 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/defineProperty +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Método(2) + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +<div>{{JSRef("Global_Objects", "Object")}}</div> + +<h2 id="summary" name="summary">Resumen</h2> + +<p>El método estático <code><strong>Object.defineProperty()</strong></code> define una nueva propiedad sobre un objeto, o modifica una ya existente, y devuelve el objeto modificado.</p> + +<div class="note"> +<p><strong>Nota:</strong> Ud. puede llamar a este método directamente mediante el constructor {{jsxref("Object")}} en vez de crear una instancia del tipo <code>Object</code>.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code>Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</code></pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto sobre el cual se define la propiedad.</dd> + <dt><code>prop</code></dt> + <dd>El nombre de la propiedad a ser definida o modificada.</dd> + <dt><code>descriptor</code></dt> + <dd>El descriptor de la propiedad que está siendo definida o modificada.</dd> +</dl> + +<h2 id="Description" name="Description">Descripción</h2> + +<p>Este método permite añadir o modificar una propiedad en un objeto.</p> + +<p>La adición normal de una propiedad a través de la asignación crea propiedades que aparecen durante la enumeración de propiedades en el bucle ({{jsxref("Sentencias/for...in", "for...in")}} o el método {{jsxref("Object.keys")}}), cuyos valores pueden modificarse y pudiendo incluso eliminar la propiedad del objeto mediante el método {{jsxref("Operadores/delete", "delete")}}.</p> + +<p>Este método nos permite modificar el comportamiento por defecto de las propiedades. Es decir, nos permite definir una propiedad como no enumerable, no modificable o incluso evitar que pueda ser eliminada del objeto.</p> + +<p>Existen dos tipos de descriptores: De datos y de acceso. Un <em><dfn>descriptor de datos</dfn></em> define una propiedad que tiene un valor, el cual puede ser o no modificado. Un descriptor de acceso define una propiedad mediante un par de funciones getter-setter que describe como se obtiene o se modifica el contenido de dicha propiedad. Un descriptor debe de ser de uno de estos dos tipos; no puede ser ambos.</p> + +<p>Ambos tipos de descriptores son objetos y comparten las siguientes claves opcionales:</p> + +<dl> + <dt><code>configurable</code></dt> + <dd><code>true</code> si y solo si el tipo de descriptor de propiedad puede modificarse y si la propiedad puede ser eliminada del correspondiente objeto.<br> + <strong>Por defecto es <code>false</code>.</strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> si y solo si dicha propiedad se muestra durante la enumeración de las propiedades del objeto correspondiente.<br> + <strong>Por defecto es <code>false</code>.</strong></dd> +</dl> + +<p>Un descriptor de datos tiene además las siguientes claves opcionales:</p> + +<dl> + <dt><code>value</code></dt> + <dd>El valor asociado a la propiedad. Puede ser cualquier tipo valido de JavaScript (number, object, function, etc).<br> + <strong>Por defecto es {{jsxref("Objetos_Globales/undefined", "undefined")}}.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>true</code> Indica si el valor de la propiedad puede modificarse con el {{jsxref("Operators/Assignment_Operators", "operador de asignación", "", 1)}}.<br> + <strong>Defaults to <code>false</code>.</strong></dd> +</dl> + +<p>Un descriptor de acceso además tiene las siguientes claves opcionales:</p> + +<dl> + <dt><code>get</code></dt> + <dd>Una función cuyo valor retornado será el que se use como valor de la propiedad.<br> + <strong>Defaults to {{jsxref("Objetos_Globales/undefined", "undefined")}}.</strong></dd> + <dt><code>set</code></dt> + <dd>Una función que recibe como único argumento el nuevo valor que se desea asignar a la propiedad y que devuelve el valor que se almacenará finalmente en el objeto.<br> + <strong>Defaults to {{jsxref("Objetos_Globales/undefined", "undefined")}}.</strong></dd> +</dl> + +<p>Hay que tener en cuenta que estas opciones también pueden heredarse; es decir, las opciones de la propiedad se han podido establecer en el prototipo de una clase de la que hereda el objeto. De modo que si queremos asegurarnos unos valores por defecto tenemos tres opciones: fijar el {{jsxref("Object.prototype")}} con {{jsxref("Object.freeze")}}, definir todas las opciones explicitamente, o establecer a {{jsxref("Objetos_Globales/null", "null")}} la propiedad {{jsxref("Object.prototype.__proto__", "__proto__")}}.</p> + +<pre class="brush: js">// Usando __proto__ +Object.defineProperty(obj, 'key', { + __proto__: null, // no aceptar propiedades heredadas + value: 'static' // no enumerable + // no configurable + // no modificable + // como opciones por defecto +}); + +// Definiendo todo explicitamente +Object.defineProperty(obj, 'key', { + enumerable: false, + configurable: false, + writable: false, + value: 'static' +}); + +// Reciclando el mismo objeto +function withValue(value) { + var d = withValue.d || ( + withValue.d = { + enumerable: false, + writable: false, + configurable: false, + value: null + } + ); + d.value = value; + return d; +} +// ... y ... +Object.defineProperty(obj, 'key', withValue('static')); + +// Si está disponible freeze, previene añadir o eliminar +//del prototipo del objeto las propiedades +// (value, get, set, enumerable, writable, configurable) +(Object.freeze || Object)(Object.prototype); +</pre> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<p>Si quiere ver algunos ejemplos de utilización del método <code>Object.defineProperty</code> con una sintaxis tipo <em>binary-flags</em>, vea <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">ejemplos adicionales</a>.</p> + +<h3 id="Example:_Creating_a_property" name="Example:_Creating_a_property">Ejemplo: Creando una propiedad</h3> + +<p>Cuando la propiedad especificada no existe en el objeto<code>, Object.defineProperty()</code> crea una nueva. En el descriptor pueden omitirse campos, a los cuales se les asignará el valor por defecto. A todos los que sean de tipo Booleano se les asignará el valor falso. Los campos <code>value</code>, <code>get</code> y <code>set</code> se establecerán por defecto a {{jsxref("Objetos_Globales/undefined", "undefined")}}. Una propiedad definida sin indicar <code>get</code>/<code>set</code>/<code>value</code>/<code>writable</code> es denominada “genérica” y “tipificada” como un descriptor de datos.</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +// Example of an object property added with defineProperty with a data property descriptor +Object.defineProperty(o, 'a', { + value: 37, + writable: true, + enumerable: true, + configurable: true +}); +// 'a' property exists in the o object and its value is 37 + +// Example of an object property added with defineProperty with an accessor property descriptor +var bValue = 38; +Object.defineProperty(o, 'b', { + get: function() { return bValue; }, + set: function(newValue) { bValue = newValue; }, + enumerable: true, + configurable: true +}); +o.b; // 38 +// 'b' property exists in the o object and its value is 38 +// The value of o.b is now always identical to bValue, unless o.b is redefined + +// You cannot try to mix both: +Object.defineProperty(o, 'conflict', { + value: 0x9f91102, + get: function() { return 0xdeadbeef; } +}); +// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors +</pre> + +<h3 id="Example:_Modifying_a_property" name="Example:_Modifying_a_property">Ejemplo: Modificando una propiedad</h3> + +<p>Cuando la propiedad realmente existe, <code>Object.defineProperty()</code> intenta modificar la propiedad de acuerdo a los valores en la descripción y la configuración actual del objeto. Si la descripción antigüa tenía su atributo de configuración establecido en <code>false</code> (la propiedad se dice "sin capacidad de configuración"), entonces ningún atributo además de los que tienen capacidad de escritura pueden ser cambiados. En ese caso, no es posible cambiar hacía atras o hacía delante entre datos y métodos de acceso de tipos de propiedades.</p> + +<p>Si una propiedad no tiene capacidad de configuración, su atributo <code>writabble</code> solo puede ser cambiada to <code>false</code>.</p> + +<p>Un {{jsxref("Global_Objects/TypeError", "TypeError")}} es arrojado cuando se intenta cambiar las propiedades de atributos sin capacidad de configuración (adeḿas del atributo <code>writable</code>) a menos que el valor actual y el valor nuevo sean los mismos.</p> + +<h4 id="Writable_attribute" name="Writable_attribute">Atributo writable</h4> + +<p>Cuando la propiedad de un atributo <code>writable</code> es establecido to <code>false</code>, la propiedad se dice esta "sin capacidad de escritura". No puede ser reasignada.</p> + +<pre class="brush: js">var o = {}; // Crea un objeto nuevo + +Object.defineProperty(o, 'a', { + value: 37, + writable: false +}); + +console.log(o.a); // logs 37 +o.a = 25; // Ningún error arrojado (lo tiraría en modo estricto, aún si el valor fuera el mismo) +console.log(o.a); // muestra 37. La asignación no funcionó +</pre> + +<p>Como es visto en el ejemplo anterior, intentar escribir en una propiedad "sin capacidad de escritura" no la cambia pero sí arroja un error.</p> + +<h4 id="Enumerable_attribute" name="Enumerable_attribute">Atributo enumerable</h4> + +<p>El atributo de la propiedad <code>enumerable</code> se define si la propiedad aparece en un ciclo {{jsxref("Statements/for...in", "for...in")}} y {{jsxref("Object.keys()")}} o no.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { value: 1, enumerable: true }); +Object.defineProperty(o, 'b', { value: 2, enumerable: false }); +Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false +o.d = 4; // enumerable defaults to true when creating a property by setting it + +for (var i in o) { + console.log(i); +} +// logs 'a' and 'd' (in undefined order) + +Object.keys(o); // ['a', 'd'] + +o.propertyIsEnumerable('a'); // true +o.propertyIsEnumerable('b'); // false +o.propertyIsEnumerable('c'); // false +</pre> + +<h4 id="Configurable_attribute" name="Configurable_attribute">Atributo configurable</h4> + +<p>El atributo <code>configurable</code> define si la propiedad puede ser eliminada del objeto, y si sus atributos (excepto <code>writable</code>) pueden ser modificados</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + get: function() { return 1; }, + configurable: false +}); + +Object.defineProperty(o, 'a', { configurable: true }); // arroja TypeError +Object.defineProperty(o, 'a', { enumerable: true }); // arroja TypeError +Object.defineProperty(o, 'a', { set: function() {} }); // arroja TypeError (set estaba definido como undefined) +Object.defineProperty(o, 'a', { get: function() { return 1; } }); // arroja TypeError (incluso aunque los get hacen lo mismo) +Object.defineProperty(o, 'a', { value: 12 }); // arroja TypeError + +console.log(o.a); // logs 1 +delete o.a; // No hace nada +console.log(o.a); // logs 1 +</pre> + +<p>Si <code>o.a</code> tuviese <code>configurable</code> a <code>true</code>, no se habrían arrojado errores y la propiedad habría sido eliminada. </p> + +<h3 id="Example:_Adding_properties_and_default_values" name="Example:_Adding_properties_and_default_values">Ejemplo: Añadiendo propiedades y valores por defecto</h3> + +<p>Es importante tener en cuenta la forma en la se aplican los valores por defecto de los atributos. Suele haber diferencias entre simplemente usar la notación con '.' y usar <code>Object.defineProperty()</code>, como se muestra en el siguiente ejemplo:</p> + +<pre class="brush: js">var o = {}; + +o.a = 1; +// es equivalente a : +Object.defineProperty(o, 'a', { + value: 1, + writable: true, + configurable: true, + enumerable: true +}); + + +// Sin embargo, +Object.defineProperty(o, 'a', { value: 1 }); +// es equivalente a : +Object.defineProperty(o, 'a', { + value: 1, + writable: false, + configurable: false, + enumerable: false +}); +</pre> + +<h3 id="Example:_Custom_setters_and_getters" name="Example:_Custom_setters_and_getters">Ejemplo: Setters y Getters a medida</h3> + +<p>Example below shows how to implement a self-archiving object. When <code>temperature</code> property is set, the <code>archive</code> array gets a log entry.</p> + +<pre class="brush: js">function Archiver() { + var temperature = null; + var archive = []; + + Object.defineProperty(this, 'temperature', { + get: function() { + console.log('get!'); + return temperature; + }, + set: function(value) { + temperature = value; + archive.push({ val: temperature }); + } + }); + + this.getArchive = function() { return archive; }; +} + +var arc = new Archiver(); +arc.temperature; // 'get!' +arc.temperature = 11; +arc.temperature = 13; +arc.getArchive(); // [{ val: 11 }, { val: 13 }] +</pre> + +<p>or</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> pattern <span class="operator token">=</span> <span class="punctuation token">{</span> + <span class="keyword token">get</span><span class="punctuation token">:</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span> <span class="string token">'I always return this string, whatever you have assigned'</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="keyword token">set</span><span class="punctuation token">:</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">this</span><span class="punctuation token">.</span>myname <span class="operator token">=</span> <span class="string token">'this is my name string'</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span><span class="punctuation token">;</span> + + +<span class="keyword token">function</span> <span class="function token">TestDefineSetAndGet</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + Object<span class="punctuation token">.</span><span class="function token">defineProperty</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">,</span> <span class="string token">'myproperty'</span><span class="punctuation token">,</span> pattern<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + + +<span class="keyword token">var</span> instance <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">TestDefineSetAndGet</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +instance<span class="punctuation token">.</span>myproperty <span class="operator token">=</span> <span class="string token">'test'</span><span class="punctuation token">;</span> +console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>instance<span class="punctuation token">.</span>myproperty<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// I always return this string, whatever you have assigned</span> + +console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>instance<span class="punctuation token">.</span>myname<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// this is my name string</span></code></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatChrome("5")}} (versiones previas sin testear)</td> + <td>{{CompatIE("9")}} ({{CompatIE("8")}}, pero solo con objetos DOM y con muchos comportamientos no estándares <a href="#Internet_Explorer_8_specific_notes">See below</a>.)</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5.1")}} ({{CompatSafari("5")}}, but not on DOM objects)</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("9")}} and above</td> + <td>{{CompatOperaMobile("11.50")}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a>.</p> + +<h3 id="Redefining_the_length_property_of_an_Array_object" name="Redefining_the_length_property_of_an_Array_object">Redefining the <code>length</code> property of an <code>Array</code> object</h3> + +<p>It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array it is possible to change the {{jsxref("Array.length", "length")}} property's value, or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.</p> + +<p>Firefox 4 through 22 will throw a {{jsxref("Global_Objects/TypeError", "TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.</p> + +<p>Versions of Chrome which implement <code>Object.defineProperty()</code> in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.</p> + +<p>Versions of Safari which implement <code>Object.defineProperty()</code> ignore a <code>length</code> value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.</p> + +<p>Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you <em>can</em> rely on it, <a href="http://whereswalden.com/2013/08/05/new-in-firefox-23-the-length-property-of-an-array-can-be-made-non-writable-but-you-shouldnt-do-it/">there's really no good reason to do so</a>.</p> + +<h3 id="Particularidades_de_Internet_Explorer_8">Particularidades de Internet Explorer 8</h3> + +<p>El método <code>Object.defineProperty()</code> de Internet Explorer <a href="http://msdn.microsoft.com/en-us/library/dd229916%28VS.85%29.aspx">sólo puede ser usado en objetos del DOM.</a> Algunas explicaciones al respecto:</p> + +<ul> + <li>Intentar usar <code>Object.defineProperty()</code> en objetos nativos produce un error.</li> + <li>Hay que definir un valor para todos los atributos de una propiedad: <code>true, true, true</code> para descriptores de datos y <code>true</code> para configurables, <code>false</code> para el descriptor de acceso <code>enumerable</code>.(?) Cualquier intento de proporcionar otro valor(?) lanzará un error.</li> + <li>Para reconfirurar una propiedad primero hay que eliminarla. Si no se elimina, la propiedad no cambia aunque se intente modificar.</li> +</ul> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li>{{jsxref("Object.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}}</li> + <li>{{jsxref("Object.prototype.watch()")}}</li> + <li>{{jsxref("Object.prototype.unwatch()")}}</li> + <li>{{jsxref("Operators/get", "get")}}</li> + <li>{{jsxref("Operators/set", "set")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">Additional <code>Object.defineProperty</code> examples</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/entries/index.html b/files/es/web/javascript/reference/global_objects/object/entries/index.html new file mode 100644 index 0000000000..98aff1178a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/entries/index.html @@ -0,0 +1,161 @@ +--- +title: Object.entries() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Object/entries +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.entries()</strong></code> devuelve una matriz de pares propios de una propiedad enumerable [key, value] de un objeto dado, en el mismo orden que es proporcionado por {{jsxref("Sentencias/for...in", "for...in")}} (La diferencia es que un bucle for-in enumera las propiedades en la cadena de prototipos).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">Object.entries(<var>obj</var>)</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>The object whose enumerable own property <code>[key, value]</code> pairs are to be returned.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>An array of the given object's own enumerable property <code>[key, value]</code> pairs.</p> + +<h2 id="Descripción">Descripción</h2> + +<p><code>Object.entries()</code> returns an array whose elements are arrays corresponding to the enumerable property <code>[key, value]</code> pairs found directly upon <code>object</code>. The ordering of the properties is the same as that given by looping over the property values of the object manually.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var obj = { foo: 'bar', baz: 42 }; +console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] + +// array like object +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] + +// array like object with random key ordering +var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.entries(an_obj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] + +// getFoo is property which isn't enumerable +var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); +my_obj.foo = 'bar'; +console.log(Object.entries(my_obj)); // [ ['foo', 'bar'] ] + +// non-object argument will be coerced to an object +console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] + +// iterate through key-value gracefully +var obj = {a: 5, b: 7, c: 9}; +for (var [key, value] of Object.entries(obj)) { + console.log(key + ' ' + value); // "a 5", "b 7", "c 9" +} + +// Or, using array extras +Object.entries(obj).forEach(([key, value]) => { + console.log(key + ' ' + value); // "a 5", "b 7", "c 9" +}); +</pre> + +<h3 id="Converting_an_Object_to_a_Map">Converting an <code>Object</code> to a <code>Map</code></h3> + +<p>The {{jsxref("Map", "new Map()")}} constructor accepts an iterable of <code>entries</code>. With <code>Object.entries</code>, you can easily convert from {{jsxref("Object")}} to {{jsxref("Map")}}:</p> + +<pre class="brush: js">var obj = { foo: 'bar', baz: 42 }; +var map = new Map(Object.entries(obj)); +console.log(map); // Map { foo: "bar", baz: 42 }</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>To add compatible <code>Object.entries</code> support in older environments that do not natively support it, you can find a Polyfill in the <a href="https://github.com/tc39/proposal-object-values-entries">tc39/proposal-object-values-entries</a> or in the <a href="https://github.com/es-shims/Object.entries">es-shims/Object.entries</a> repositories.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.entries', 'Object.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-object.entries', 'Object.entries')}}</td> + <td>{{Spec2('ES8')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(54)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(47)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari(10.1)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(54)}}</td> + <td>{{CompatChrome(54)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(47)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.values()")}} {{experimental_inline}}</li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/freeze/index.html b/files/es/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..890d0d07b4 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,174 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.freeze()</strong></code> <em>congela</em> un objeto, es decir: impide que se le agreguen nuevas propiedades; impide que se puedan eliminar las propiedades ya existentes; impide que dichas propiedades, o su capacidad de enumeración, configuración, o escritura, puedan ser modificadas; impide también que se pueda modificar su prototipo. El método devuelve el objeto recibido.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-freeze.html")}}</div> + +<p class="hidden">El código de este ejemplo interactivo está almacenado en un repositorio de GitHub. Si quieres contribuir al proyecto de ejemplos interactivos, puedes clonar <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> y enviarnos un <em>pull request</em>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code>Object.freeze(<var>obj</var>)</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto a <em>congelar</em>.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>El mismo objeto</p> + +<h2 id="Descripción">Descripción</h2> + +<p>Nada puede ser agregado o removido de las propiedades establecidas de un objeto <em>congelado</em>. Cualquier intento de hacerlo fallará, ya sea de manera silenciosa o <em>arrojando una excepción </em>{{jsxref("TypeError")}} (más comunmente, pero no exclusivamente, en {{jsxref("Strict_mode", "strict mode", "", 1)}}).</p> + +<p>Los valores no pueden ser cambiados por propiedades de datos. Propiedades de acceso (<em>getters</em> y <em>setters</em>) funcionan igual (y aún dan la ilusión de que estas cambiando el valor). Note que los valores que son objetos aún pueden ser modificados, a menos que esten <em>congelados</em> tambien.</p> + +<p>La función retorna el mismo objeto pasado en ella, no crea una copia <em>congelada</em></p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Congelando_Objetos">Congelando Objetos</h3> + +<pre class="brush: js">var obj = { + prop: function() {}, + foo: 'bar' +}; + +// Nuevas propiedades pueden ser agregadas, +// propiedades existentes pueden cambiar o removerse +obj.foo = 'baz'; +obj.lumpy = 'woof'; +delete obj.prop; + +// Ambos, el objeto pasado como argumento tanto como el que se regresa +// serán congelados +// Es innecesario salvar el objeto que es regresado en orden de <em>congelar</em> +// el original. +var o = Object.freeze(obj); + +assert(Object.isFrozen(obj) === true); + +// Ahora cualquier cambio fallará +obj.foo = 'quux'; // No hace nada de manera silenciosa +obj.quaxxor = 'the friendly duck'; // No agrega una nueva propiedad, de manera silenciosa + +// ...y en modo estrico tal intento arrojará TypeErrors +function fail(){ + 'use strict'; + obj.foo = 'sparky'; // arroja un TypeError + delete obj.quaxxor; // arroja un TypeError + obj.sparky = 'arf'; // arroja un TypeError +} + +fail(); + +// Los intentos utilizando Object.defineProperty tambien arrojarán una excepción... +Object.defineProperty(obj, 'ohai', { value: 17 }); // arroja un TypeError +Object.defineProperty(obj, 'foo', { value: 'eit' }); // arroja un TypeError + +// Es imposible cambiar un prototipo +// Estos ejemplos retornan un error TypeError +Object.setPrototype(obj,{x:20}) +obj.__proto__ = {x:20} +</pre> + +<p>El siguiente ejemplo muestra que los valores de objetos en un objeto congelado pueden ser mutados (la congelación es superficial).</p> + +<pre class="brush: js">obj1 = { + internal: {} +}; + +Object.freeze(obj1); +obj1.internal.a = 'aValue'; + +obj1.internal.a // 'aValue' + +// Para hacer obj completamente inmutable, congelamos cada objeto en obj. +// Para hacerlo, usamos esta función. +function deepFreeze(obj) { + + // Recuperamos el nombre de las propiedades en obj + var propNames = Object.getOwnPropertyNames(obj); + + // Congelamos las propiedades antes de congelar a obj + propNames.forEach(function(name) { + var prop = obj[name]; + + // Si la propiedad es un objeto, llamaremos a deepFreezze para que congele las propiedades de ese objeto + if (typeof prop == 'object' && prop !== null && !Object.isFrozen(prop)) + deepFreeze(prop); + }); + + // congelamos a obj + return Object.freeze(obj); +} + +obj2 = { + internal: {} +}; + +deepFreeze(obj2); +obj2.internal.a = 'anotherValue'; +obj2.internal.a; // undefined +</pre> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el argumento pasado a este método no es un objeto (un primitivo), entonces causará un {{jsxref("TypeError")}}. En ES6, un argumento no-objeto será tratado como si fuera un objeto <em>congelado</em> cualquiera, simplemente lo regresa.</p> + +<pre class="brush: js">> Object.freeze(1) +TypeError: 1 is not an object // Código ES5 + +> Object.freeze(1) +1 // Código ES6 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementado en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{Compat("javascript.builtins.Object.freeze")}}</p> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/fromentries/index.html b/files/es/web/javascript/reference/global_objects/object/fromentries/index.html new file mode 100644 index 0000000000..023cc5f8ca --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/fromentries/index.html @@ -0,0 +1,106 @@ +--- +title: Object.fromEntries() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/fromEntries +tags: + - JavaScript + - Objeto + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/fromEntries +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.fromEntries()</strong></code> transforma una lista de pares con <code>[clave-valor] </code>en un objeto.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-fromentries.html")}}</div> + + + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate">Object.fromEntries(<var>iterable</var>);</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code><var>iterador</var></code></dt> + <dd>Un iterador como {{jsxref("Array")}}, {{jsxref("Map")}} u otros objetos que implementen el <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">protocolo iterable</a>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un nuevo objeto cuyas propiedades son dadas por las entradas del iterador.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>El método <code>Object.fromEntries()</code> toma una lista de pares con clave-valor y devuelve un nuevo objeto cuyas propiedades son dadas por éstas entradas. El argumento <em>iterador </em>se espera que sea un objeto que implemente un método <code>@@iterator</code>, que devuelve un objeto iterador, que produce un objeto tipo array de dos elementos, donde el primer elemento es un valor que se usará como la clave de la propiedad, y el segundo elemento es el valor a asociar con esa clave de propiedad.</p> + +<p><code>Object.fromEntries()</code> realiza lo inverso de {{jsxref("Object.entries()")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Convirtiendo_un_Map_en_un_Objeto">Convirtiendo un <code>Map</code> en un <code>Objeto</code></h3> + +<p>Con <code>Object.fromEntries</code>, puedes convertir de un {{jsxref("Map")}} a un {{jsxref("Object")}}:</p> + +<pre class="brush: js notranslate">const map = new Map([ ['foo', 'bar'], ['baz', 42] ]); +const obj = Object.fromEntries(map); +console.log(obj); // { foo: "bar", baz: 42 } +</pre> + +<h3 id="Convirtiendo_un_Arreglo_en_un_Objeto">Convirtiendo un <code>Arreglo</code> en un <code>Objeto</code></h3> + +<p>Con <code>Object.fromEntries</code>, puedes convertir de un {{jsxref("Array")}} a un {{jsxref("Object")}}:</p> + +<pre class="brush: js notranslate">const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; +const obj = Object.fromEntries(arr); +console.log(obj); // { 0: "a", 1: "b", 2: "c" } +</pre> + +<h3 id="Transformación_de_Objetos">Transformación de Objetos</h3> + +<p>Con <code>Object.fromEntries</code>, su método inverso {{jsxref("Object.entries()")}}, y <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2">array métodos de manipulaciín de arreglos</a>, puedes transformar objetos así:</p> + +<pre class="brush: js notranslate">const object1 = { a: 1, b: 2, c: 3 }; + +const object2 = Object.fromEntries( + Object.entries(object1) + .map(([ key, val ]) => [ key, val * 2 ]) +); + +console.log(object2); +// { a: 2, b: 4, c: 6 }</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.fromentries', 'Object.fromEntries')}}</td> + <td>Etapa 4</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + + + +<p>{{Compat("javascript.builtins.Object.fromEntries")}}</p> + +<h2 id="Véase_tambien">Véase tambien</h2> + +<ul> + <li>{{jsxref("Object.entries()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.values()")}}</li> + <li>{{jsxref("Map.prototype.entries()")}}</li> + <li>{{jsxref("Map.prototype.keys()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html b/files/es/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html new file mode 100644 index 0000000000..fb2eaf68da --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html @@ -0,0 +1,161 @@ +--- +title: Object.getOwnPropertyDescriptor() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/getOwnPropertyDescriptor +tags: + - ECMAScript5 + - JavaScript + - Método(2) + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.getOwnPropertyDescriptor()</strong></code> regresa como descripción de propiedad para una propiedad propia (eso es, una presente directamente en el objeto, no presente por la fuerza a través de la cadena de prototipo del objeto) de un objeto dado.</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="syntaxbox"><code>Object.getOwnPropertyDescriptor(<var>obj</var>, <var>prop</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto en el que se busca la propiedad.</dd> + <dt><code>prop</code></dt> + <dd>El nombre de la propiedad del cuál se obtendrá la descripción.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un descriptor de propiedad de una propiedad dada si existe en el objeto, {{jsxref("undefined")}} en cualquier otro caso.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>Éste método permite la examinación precisa de la descripción de una propiedad. Una propiedad en JavaScript consiste de el nombre de una cadena de valor y un descriptor de propiedad. Información más detallada acerca de los tipos de descripciones y sus atributos puede ser encontrada en {{jsxref("Object.defineProperty()")}}.</p> + +<p>Una descripción de propiedad es un registro con alguno de los siguientes atributos:</p> + +<dl> + <dt><code>value</code></dt> + <dd>El valor asociado con la propiedad (descriptores de datos unicamente).</dd> + <dt><code><strong>writable</strong></code></dt> + <dd><code>true</code> si y solo si el valor asociado con la propiedad puede ser cambiada (descriptores de datos unicamente).</dd> + <dt><code>get</code></dt> + <dd>Una función que sirve como método de acceso para la propiedad, o {{jsxref("undefined")}} si no hay método de acceso (métodos de acceso de descripciones unicamente).</dd> + <dt><code>set</code></dt> + <dd>Una función que sirve como método de establecimiento para la propieda, o {{jsxref("undefined")}} si no hay método de establecimiento (métodos de establecimiento de descripciones unicamente).</dd> + <dt><code>configurable</code></dt> + <dd><code>true</code> si y solo si el tipo de ésta descripción de propiedad puede ser cambiada y si la propiedad puede ser eliminada del objeto correspondiente.</dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> si y solo si ésta propiedad aparece durante la enumeración de las propiedades del objeto correspondiente.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var o, d; + +o = { get foo() { return 17; } }; +d = Object.getOwnPropertyDescriptor(o, 'foo'); +// d is { configurable: true, enumerable: true, get: /* la función de acceso */, set: undefined } + +o = { bar: 42 }; +d = Object.getOwnPropertyDescriptor(o, 'bar'); +// d is { configurable: true, enumerable: true, value: 42, writable: true } + +o = {}; +Object.defineProperty(o, 'baz', { value: 8675309, writable: false, enumerable: false }); +d = Object.getOwnPropertyDescriptor(o, 'baz'); +// d es { value: 8675309, writable: false, enumerable: false, configurable: false } +</pre> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el primer argumento que se le pasa a éste método no es un objeto (primitivo), entonces causará un {{jsxref("TypeError")}}. En ES6, un no-objeto pasado como primer argumento será convertido (coerción) a un objeto en primera instancia.</p> + +<pre class="brush: js">Object.getOwnPropertyDescriptor("foo", 0); +// TypeError: "foo" is not an object // Código ES5 + +Object.getOwnPropertyDescriptor("foo", 0); +// {configurable:false, enumerable:true, value:"f", writable:false} // Código ES6 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.3', 'Object.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementado en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getownpropertydescriptor', 'Object.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatIE("8")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Reflect.getOwnPropertyDescriptor()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.html b/files/es/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.html new file mode 100644 index 0000000000..9585fa80e8 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.html @@ -0,0 +1,117 @@ +--- +title: Object.getOwnPropertyDescriptors() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/getOwnPropertyDescriptors +tags: + - JavaScript + - Objeto + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors +--- +<div>{{JSRef}}</div> + +<p>El método<code><strong>Object.getOwnPropertyDescriptors()</strong></code><strong> </strong>regresa todos los descriptores de propiedad propios de un objeto dado.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-getownpropertydescriptors.html")}}</div> + +<h2 id="Sintáxis">Sintáxis</h2> + +<pre class="syntaxbox">Object.getOwnPropertyDescriptors(<var>obj</var>)</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto para el cual obtener todos los descriptores de propiedad.</dd> +</dl> + +<h3 id="Valores_devueltos">Valores devueltos</h3> + +<p>Un objeto que contiene todos los descriptores de propiedad propios de un objeto.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>Este método permite la examinación de la descripción precisa de todas las propiedades de un objeto. Una propiedad en JavaScript consiste en un valor-cadena nombre y un descriptor de propiedad. Más información acerca de los tipos de descriptores de propiedad y sus atributos pueden ser encontrados en {{jsxref("Object.defineProperty()")}}.</p> + +<p>Un descriptor de propiedad es un registro con algunos de los siguientes atributos:</p> + +<dl> + <dt><code>value</code></dt> + <dd>El valor asociado con la propiedad (solo descriptores de datos).</dd> + <dt><code><strong>writable</strong></code></dt> + <dd><code>true</code> si y solo si el valor asociado con la propiedad puede ser cambiado (solo descriptores de datos).</dd> + <dt><code>get</code></dt> + <dd>Un función que sirve como un getter para la propiedad, o {{jsxref("undefined")}} si no hay getter (solo descriptores de acceso).</dd> + <dt><code>set</code></dt> + <dd>Una función que sirve como un setter para la propiedad, o {{jsxref("undefined")}} si no hay setter (solo descriptores de acceso).</dd> + <dt><code>configurable</code></dt> + <dd><code>true</code> si y solo si el tipo de este descriptor de propiedad puede ser cambiado y si la propiedad puede ser borrada de el objeto correspondiente.</dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> si y solo si esta propiedad aparece durante la enumeración de las propiedad en el objeto correspondiente.</dd> +</dl> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Creando_un_clon_superficial">Creando un clon superficial</h3> + +<p>Mientras el método {{jsxref("Object.assign()")}} solo copiará las propiedades enumerables y propias de un objeto fuente a un objeto destino, puedes usar este método y {{jsxref("Object.create()")}} para una copia superficial entre dos objetos desconocidos:</p> + +<pre class="brush: js">Object.create( + Object.getPrototypeOf(obj), + Object.getOwnPropertyDescriptors(obj) +); +</pre> + +<h3 id="Creando_una_subclase">Creando una subclase</h3> + +<p>Una manera típica de crear una subclase es definir la subclase, establecer su prototipo a una instancia de la superclase, y después definir propiedades en esa instancia. Esto puede ponerse incómodo especialmente por los getters y setters. En cambio, tú puedes usar este código para establecer el prototipo:</p> + +<pre class="brush: js">function superclass() {} +superclass.prototype = { + // Define tus métodos y propiedades aquí +}; +function subclass() {} +subclass.prototype = Object.create( + superclass.prototype, + { + // Define tus métodos y propiedades aquí + } +); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.getownpropertydescriptors', 'Object.getOwnPropertyDescriptors')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definición inicial en ECMAScript 2017.</td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-object.getownpropertydescriptors', 'Object.getOwnPropertyDescriptors')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> +<div class="hidden">La tabla de compatibilidad en esta página es generada a partir de datos estructurados. Si quisieras contribuir con los datos, por favor vaya a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> mándenos una petición pull.</div> + +<p>{{Compat("javascript.builtins.Object.getOwnPropertyDescriptors")}}</p> +</div> + +<h2 id="Ver_también">Ver también:</h2> + +<ul> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li><a href="https://github.com/tc39/proposal-object-getownpropertydescriptors">Polyfill</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/getownpropertynames/index.html b/files/es/web/javascript/reference/global_objects/object/getownpropertynames/index.html new file mode 100644 index 0000000000..5c3819045a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/getownpropertynames/index.html @@ -0,0 +1,163 @@ +--- +title: Object.getOwnPropertyNames() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/getOwnPropertyNames +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames +--- +<div> + {{JSRef("Global_Objects", "Object")}}</div> +<h2 id="Summary" name="Summary">Resumen</h2> +<p>El método <code><strong>Object.getOwnPropertyNames()</strong></code> devuelve un array con todas las propiedades (numerables o no) encontradas en un objeto dado.</p> +<h2 id="Syntax" name="Syntax">Sintaxis</h2> +<pre class="syntaxbox"><code>Object.getOwnPropertyNames(<em>obj</em>)</code></pre> +<h3 id="Parameters" name="Parameters">Parámetros</h3> +<dl> + <dt> + obj</dt> + <dd> + El objeto cuyas propiedades directas, numerables <em>y no-numerables</em>, serán devueltas.</dd> +</dl> +<h2 id="Description" name="Description">Descripción</h2> +<p><code>Object.getOwnPropertyNames</code> devuelve un array cuyos elementos son <em>strings </em>correspondientes a cada una de las propiedades encontradas directamente en <code>obj</code>. El orden de las propiedades numerables en el array coincide con el expuesto para <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in loop</a> (o para {{jsxref("Object.keys")}}) con respecto a las propiedades del object. El orden de las propiedades no-numerables del array, y de éstas respecto a las numerables, no está definido.</p> +<h2 id="Ejemplos">Ejemplos</h2> +<pre class="brush: js">var arr = ["a", "b", "c"]; +print(Object.getOwnPropertyNames(arr).sort()); // imprime "0,1,2,length" + +// Objeto similar a Array +var obj = { 0: "a", 1: "b", 2: "c"}; +print(Object.getOwnPropertyNames(obj).sort()); // imprime "0,1,2" + +// Imprime nombres de variables y valores usando Array.forEach +Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) { + print(val + " -> " + obj[val]); +}); +// imprime +// 0 -> a +// 1 -> b +// 2 -> c + +// propiedad no-numerable +var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; }, enumerable: false } }); +my_obj.foo = 1; + +print(Object.getOwnPropertyNames(my_obj).sort()); // imprime "foo, getFoo" +</pre> +<p>Si se quiere solo las propiedades numerables, ver {{jsxref("Object.keys")}} o usar un <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in loop</a> (aunque esto devolvería propiedades numerables no directas del <span style="line-height: 1.5;">objeto pertenecientes a la cadena de <em>prototype</em> a la que pertenezca, a menos que finalmente se filtre con hasOwnProperty()).</span></p> +<p>Items de la cadena <em>prototype</em> no se listan:</p> +<pre class="brush: js">function ParentClass () { +} +ParentClass.prototype.inheritedMethod = function () { +}; + +function ChildClass () { + this.prop = 5; + this.method = function () {}; +} +ChildClass.prototype = new ParentClass; +ChildClass.prototype.prototypeMethod = function () { +}; + +alert( + Object.getOwnPropertyNames( + new ChildClass() // ["prop", "method"] + ) +) +</pre> +<h3 id="Get_Non-Enumerable_Only">Get Non-Enumerable Only</h3> +<p>Aquí se usa la función Array.prototype.filter para quitar las <em>keys</em> numerables (obtenidas con Object.keys) de una lista con todas las <em>keys</em> (obtenida con Object.getOwnPropertynames) dejando solo las no-numerables.</p> +<pre class="brush: js">var target = myObject; +var enum_and_nonenum = Object.getOwnPropertyNames(target); +var enum_only = Object.keys(target); +var nonenum_only = enum_and_nonenum.filter(function(key) { + var indexInEnum = enum_only.indexOf(key) + if (indexInEnum == -1) { + //no encontrada en las keys de enum_only, por lo que se trata de una key numerable, se devuelve true para mantenerla en filter + return true; + } else { + return false; + } +}); + +console.log(nonenum_only); +</pre> +<h2 id="Especificaciones">Especificaciones</h2> +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Status</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.4', 'Object.getOwnPropertyNames')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition.<br> + Implemented in JavaScript 1.8.5</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getownpropertynames', 'Object.getOwnPropertyNames')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> +<h2 id="Compatibilidad_con_Navegadores"> Compatibilidad con Navegadores</h2> +<div> + {{CompatibilityTable}}</div> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>4 (2.0)</td> + <td>5</td> + <td>9</td> + <td>12</td> + <td>5</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> + </table> +</div> +<p>Based on <a href="http://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p> +<h3 id="SpiderMonkey-specific_notes">SpiderMonkey-specific notes</h3> +<ul> + <li>Prior to SpiderMonkey 28 {{geckoRelease("28")}}, <code>Object.getOwnPropertyNames</code> did not see unresolved properties of {{jsxref("Error")}} objects. This has been fixed in later versions ({{bug("724768")}}).</li> +</ul> +<h2 id="See_also" name="See_also">Ver también</h2> +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties" title="Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.prototype.hasOwnProperty")}}</li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable")}}</li> + <li>{{jsxref("Object.create")}}</li> + <li>{{jsxref("Object.keys")}}</li> + <li>{{jsxref("Array.forEach()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/getownpropertysymbols/index.html b/files/es/web/javascript/reference/global_objects/object/getownpropertysymbols/index.html new file mode 100644 index 0000000000..cf8be23f59 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/getownpropertysymbols/index.html @@ -0,0 +1,123 @@ +--- +title: Object.getOwnPropertySymbols() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/getOwnPropertySymbols +tags: + - ECMAScript6 + - Experimental + - JavaScript + - Método(2) + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.getOwnPropertySymbols()</strong></code> regresa una colección de todos las propiedades de los simbolos encontrados directamente en un objeto dado.</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="syntaxbox"><code>Object.getOwnPropertySymbols(<var>obj</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto del cual los simbolos de propiedades son devueltos.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Similar a {{jsxref("Object.getOwnPropertyNames()")}}, puedes obtener todas las propiedades de simbolos de un objeto dado como una colección de simbolos. Note que {{jsxref("Object.getOwnPropertyNames()")}} no contiene en sí mismo las propiedades de simbolos de un objeto y solo contiene las propiedades de cadenas.</p> + +<p>Cómo todos los objetos no tienen inicialmente propiedades simbolos propios, <code>Object.getOwnPropertySymbols()</code> regresa una colección vacia a menos que tengas propiedades de simbolos establecidas en tu objeto.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var obj = {}; +var a = Symbol('a'); +var b = Symbol.for('b'); + +obj[a] = 'localSymbol'; +obj[b] = 'globalSymbol'; + +var objectSymbols = Object.getOwnPropertySymbols(obj); + +console.log(objectSymbols.length); // 2 +console.log(objectSymbols); // [Symbol(a), Symbol(b)] +console.log(objectSymbols[0]); // Symbol(a) +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getownpropertysymbols', 'Object.getOwnPropertySymbols')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop("36.0")}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>5.1</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile("36.0")}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Symbol")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/es/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..a9b50ec2ec --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,137 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/getPrototypeOf +tags: + - ECMAScript5 + - JavaScript + - Objeto + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +<div>{{JSRef("Global_Objects", "Object")}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>El método <code><strong>Object.getPrototypeOf()</strong></code> devuelve el prototipo (es decir, el valor de la propiedad interna <code>[[Prototype]]</code>) del objeto especificado.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><code>Object.getPrototypeOf(<var>obj</var>)</code></pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto cuyo prototipo va a ser devuelto.</dd> +</dl> + +<h3 id="Valor_Devuelto">Valor Devuelto</h3> + +<p>El prototipo del objeto dado. Si no existen propiedades heredadas se devolverá {{jsxref("null")}}.</p> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<pre class="brush: js">var proto = {}; +var obj= Object.create(proto); +Object.getPrototypeOf(obj) === proto; // true +</pre> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>En ES5, lanzará una excepción {{jsxref("Global_Objects/TypeError", "TypeError")}} si el parámetro <code>obj</code> no es un objeto. en ES6, El parámetro será forzado a un {{jsxref("Global_Objects/Object", "Object")}}.</p> + +<pre class="brush: js">> Object.getPrototypeOf('foo') +TypeError: "foo" is not an object // ES5 code +> Object.getPrototypeOf('foo') +String.prototype // ES6 code +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12.10")}} (tal vez en las últimas versiones)</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p> + +<h3 id="Notas_espécificas_sobre_Opera">Notas espécificas sobre Opera</h3> + +<p>A pesar de que las versiones anteriores de opera no soportan aun <code>Object.getPrototypeOf()</code>, Opera soporta la propiedad no estándar {{jsxref("Object.proto", "__proto__")}} desde Opera 10.50.</p> + +<h2 id="See_also" name="See_also">Mira también</h2> + +<ul> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}</li> + <li>John Resig's post on <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf</a></li> + <li>{{jsxref("Object.prototype.__proto__")}}</li> + <li>{{jsxref("Reflect.getPrototypeOf()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/es/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..d84e5d6a52 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,186 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/hasOwnProperty +tags: + - JavaScript + - Method + - Object + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +<div>{{JSRef("Objetos_globales", "Object")}}</div> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p>El método <code><strong>hasOwnProperty()</strong></code> devuelve un booleano indicando si el objeto tiene la propiedad especificada.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><code><em>obj</em>.hasOwnProperty(<em>prop</em>)</code></pre> + +<h3 id="Parameters" name="Parameters">Parámetros</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>El nombre de la propiedad a buscar.</dd> +</dl> + +<h2 id="Description" name="Description">Descripción</h2> + +<p>Todo objeto descendiente de <code>Object</code> hereda el método <code>hasOwnProperty</code>. Este método puede ser usando para determinar si un objeto tiene la propiedad especificada como una propiedad directa de ese objeto; a diferencia del operador {{jsxref("Operators/in", "in")}}, este método no verifica la cadena prototipo del objeto.</p> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<h3 id="Example:_Using_hasOwnProperty_to_test_for_a_property.27s_existence" name="Example:_Using_hasOwnProperty_to_test_for_a_property.27s_existence">Ejemplo: usar <code>hasOwnProperty</code> para comprobar la existencia de una propiedad</h3> + +<p>El siguiente ejemplo determina si el objeto <code>o</code> contiene una propiedad llamada <code>prop</code>:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'exists'; + +function changeO() { + o.newprop = o.prop; + delete o.prop; +} + +o.hasOwnProperty('prop'); // returns true +changeO(); +o.hasOwnProperty('prop'); // returns false</pre> + +<h3 id="Example:_Direct_versus_inherited_properties" name="Example:_Direct_versus_inherited_properties">Ejemplo: Directo versus propiedades heredadas</h3> + +<p>El siguiente ejemplo diferencia entre propiedades directas y propiedades heredadas a través de la cadena prototype:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'exists'; +o.hasOwnProperty('prop'); // returns true +o.hasOwnProperty('toString'); // returns false +o.hasOwnProperty('hasOwnProperty'); // returns false</pre> + +<h3 id="Example:_Itarate_over_properties_not_considering_inherited_properties" name="Example:_Itarate_over_properties_not_considering_inherited_properties">Ejemplo: Iterando sobre las propiedades de un objeto</h3> + +<p>El siguiente ejemplo muestra como iterar sobre las propiedades de un objeto sin ejecutar sobre propiedades heredadas. Observe que el bucle for..in ya está no solo iterando elementos enumerables, por consiguiente uno no debería asumir que basado en la falta de propiedades no numerales mostrando en el bucle que hasOwnProperty por si misma no está solo es estrictamente para iterar elementos numerados (como con {{jsxref("Object.getOwnPropertyNames()")}}).</p> + +<pre class="brush: js">var buz = { + fog: 'stack' +}; + +for (var name in buz) { + if (buz.hasOwnProperty(name)) { + alert("this is fog (" + name + ") for sure. Value: " + buz[name]); + } + else { + alert(name); // toString or something else + } +}</pre> + +<h3 id="Ejemplo_hasOwnProperty_como_una_propiedad">Ejemplo: <code>hasOwnProperty</code> como una propiedad</h3> + +<p>JavaScript no protege el nombre de la propiedad <code>hasOwnProperty</code>; en consecuencia, si existe la posibilidad de que un objeto pudiera tener la propiedad con ese nombre, es necesario usar un externo <code>hasOwnProperty</code> para obtener los correctos resultados:</p> + +<pre class="brush: js">var foo = { + hasOwnProperty: function() { + return false; + }, + bar: 'Here be dragons' +}; + +foo.hasOwnProperty('bar'); // always returns false + +// Use another Object's hasOwnProperty and call it with 'this' set to foo +({}).hasOwnProperty.call(foo, 'bar'); // true + +// It's also possible to use the hasOwnProperty property from the Object property for this purpose +Object.prototype.hasOwnProperty.call(foo, 'bar'); // true +</pre> + +<p>Observe que en el último caso no han habido nuevos objetos creados.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>ECMAScript 3rd Edition. Implemented in JavaScript 1.5</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_Also" name="See_Also">Véase también</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties" title="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></li> + <li>{{jsxref("Operators/in", "in")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited">JavaScript Guide: Inheritance revisted</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/index.html b/files/es/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..99089bd28e --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,187 @@ +--- +title: Object +slug: Web/JavaScript/Referencia/Objetos_globales/Object +tags: + - Constructor + - JavaScript + - Objeto + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<div>La clase Object representa uno de los tipos de datos de Javascript. Es es usado para guardar una colección de datos definidos y entidades más complejas. Los objetos pueden ser creados utilzando el constructor {{jsxref("Object/Object", "Object()")}} o la sintaxis literal de objeto. </div> + +<p>El constructor <code><strong>Object</strong></code> crea una envoltura al objeto.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + + + +<pre class="syntaxbox notranslate">// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Los pares de nombres (strings) y los valores (cualquier valor) donde los nombres son separados por una coma.</dd> + <dt><code>valor</code></dt> + <dd>Cualquier valor.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>El constructor <code>Object</code> crea una envoltura de objeto al valor dado. Si el valor es {{jsxref("null")}} o {{jsxref("undefined")}}, creará y retornará un objeto vacío, de otra forma, retornará un objeto de un tipo que corresponda al valor dado. Si el valor ya es un objeto devolverá el valor.</p> + +<p>Cuando es llamano en un contexto non-constructor, <code>Object </code>se comportará indenticamente a <code>new Object()</code>.</p> + +<p>Ver <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Propiedades_del_constructor_Object">Propiedades del constructor <code>Object</code></h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Tiene un valor de 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Permite añadir propiedades a todos los objetos del tipo Object.</dd> +</dl> + +<h2 id="Métodos_del_constructor_Object">Métodos del constructor <code>Object</code></h2> + +<dl> + <dt>{{jsxref("Object.assign()")}}</dt> + <dd>Copia los valores de todas sus propiedades enumerables desde uno o más objetos fuente a un objeto destino.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Crea un nuevo objeto con el prototipo objeto y propiedades específicadas.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Añade la propiedad nombrada descrita por un descriptor dado a un objeto.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Agrega las propiedades nombradas descritas por los descriptores dados a un objeto.</dd> + <dt>{{jsxref("Object.entries()")}}</dt> + <dd>Returns an array containing all of the <code>[key, value]</code> pairs of a given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.fromEntries()")}}</dt> + <dd>Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptors()")}}</dt> + <dd>Returns an object containing all own property descriptors for an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}}</dt> + <dd>Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property).</dd> + <dt>{{jsxref("Object.values()")}}</dt> + <dd>Returns an array containing the values that correspond to all of a given object's <strong>own</strong> enumerable string properties.</dd> +</dl> + +<h2 id="Object_instances_and_Object_prototype_object"><code>Object</code> instances and <code>Object</code> prototype object</h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}</div> + +<h2 id="Deleting_a_property_from_an_object">Deleting a property from an object</h2> + +<p>There isn't any method in an Object itself to delete its own properties (e.g. like <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete">Map.prototype.delete()</a></code>). To do so one has to use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete operator</a>.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Object_given_undefined_and_null_types">Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>The following examples store an empty <code>Object</code> object in <code>o</code>:</p> + +<pre class="brush: js notranslate">var o = new Object(); +</pre> + +<pre class="brush: js notranslate">var o = new Object(undefined); +</pre> + +<pre class="brush: js notranslate">var o = new Object(null); +</pre> + +<h3 id="Using_Object_to_create_Boolean_objects">Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>The following examples store {{jsxref("Boolean")}} objects in <code>o</code>:</p> + +<pre class="brush: js notranslate">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js notranslate">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/is/index.html b/files/es/web/javascript/reference/global_objects/object/is/index.html new file mode 100644 index 0000000000..926357d0ab --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/is/index.html @@ -0,0 +1,172 @@ +--- +title: Object.is() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/is +tags: + - Comparación + - Condición + - ECMAScript2015 + - JavaScript + - Objeto + - condicional + - igualdad + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/is +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.is()</strong></code> determina si dos valores <a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">son iguales</a>.</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="syntaxbox notranslate"><code>Object.is(<var>valor1</var>, <var>valor2</var>);</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>valor1</code></dt> + <dd>Primer valor a comparar.</dd> + <dt><code>valor2</code></dt> + <dd>Segundo valor a comparar.</dd> +</dl> + +<h3 id="Valor_return_del_método">Valor return del método</h3> + +<p>Este método devuelve un valor de tipo {{jsxref("Boolean")}} indicando si los valores pasados como parámetros son iguales o no.</p> + +<h2 id="Descripción">Descripción</h2> + +<p><code>Object.is()</code> determina si dos valores <a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">son iguales</a>. Dos valores son iguales si se puede asegurar que:</p> + +<ul> + <li>ambos son {{jsxref("undefined")}}</li> + <li>ambos son {{jsxref("null")}}</li> + <li>ambos son <code>true</code> o <code>false</code></li> + <li>ambos son strings y tienen la misma longitud con los mismos carácteres</li> + <li>ambos son el mismo objeto</li> + <li>ambos son números y + <ul> + <li><code>ambos +0 (mayores que 0)</code></li> + <li><code>ambos -0 (menores que 0)</code></li> + <li>ambos son {{jsxref("NaN")}}</li> + <li>o ambos no son cero o no son de tipo {{jsxref("NaN")}} y tienen el mismo valor</li> + </ul> + </li> +</ul> + +<p>Esta comparación <em>no</em> es igual a la que realiza el operador {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}. El operador {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} aplica varias coerciones(comprobaciones) en ambos sentidos (si no tienen el mismo Type) antes de probar la igualdad (lo que resulta en comportamientos como <code>"" == false</code> siendo <code>true</code>), pero <code>Object.is</code> no obliga a niguno de los valores.</p> + +<p>Esta <em>tampoco</em> es igual a la que realiza el operador {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}. El operador {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} (y el operador {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}) trata los valores <code>-0</code> <code>y +0</code> como iguales, y además, trata {{jsxref("Number.NaN")}} como no igual a {{jsxref("NaN")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js notranslate">Object.is('foo', 'foo'); // true +Object.is(window, window); // true + +Object.is('foo', 'bar'); // false +Object.is([], []); // false + +var test = { a: 1 }; +Object.is(test, test); // true + +Object.is(null, null); // true + +// Special Cases +Object.is(0, -0); // false +Object.is(-0, -0); // true +Object.is(NaN, 0/0); // true +</pre> + +<h2 id="Polyfill_para_navegadores_no_ES6"><a href="https://en.wikipedia.org/wiki/Polyfill">Polyfill</a> para navegadores no ES6</h2> + +<p><code>Object.is()</code> es una adición propuesta en el estandar ECMA-262; y como tal, puede no estar presente en todos los navegadores. Para los casos en que no tenga disponible este método, podría utilizar este código haciendolo que se cargue antes que cualquier otro script. Esto permite que puedas utilizar <code>Object.is()</code> en los navegadores que no lo llevan incluído.</p> + +<pre class="brush: js notranslate">if (!Object.is) { + Object.is = function(x, y) { + // SameValue algorithm + if (x === y) { // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return x !== 0 || 1 / x === 1 / y; + } else { + // Step 6.a: NaN == NaN + return x !== x && y !== y; + } + }; +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.is', 'Object.is')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("30")}}</td> + <td>{{CompatGeckoDesktop("22")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("22")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="sect1"></h2> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Web/JavaScript/Equality_comparisons_and_sameness">Comparadores de igualdad e identidad</a> —Una comparación de las 3 operaciones de cotejamiento integradas.</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/isextensible/index.html b/files/es/web/javascript/reference/global_objects/object/isextensible/index.html new file mode 100644 index 0000000000..30082032ea --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/isextensible/index.html @@ -0,0 +1,144 @@ +--- +title: Object.isExtensible() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/isExtensible +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Objeto + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isExtensible +--- +<div>{{JSRef}}</div> + +<p>El método <strong><code>Object.isExtensible()</code></strong> determina si un objeto es extendible (si puede tener propiedades nuevas agregadas a éste).</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="syntaxbox"><code>Object.isExtensible(<var>obj</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto a ser revisado.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Los objetos son extendibles por defecto: ellos pueden tener propiedades nuevas agregadas a ellos, y (en motores que soportan {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} la propiedad __proto__) pueden ser modificados. Un objeto puede ser marcado como no extendible usando {{jsxref("Object.preventExtensions()")}}, {{jsxref("Object.seal()")}}, o {{jsxref("Object.freeze()")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">// Los Objetos nuevos son extendibles (por defecto). +var empty = {}; +Object.isExtensible(empty); // === true + +// ...pero eso puede cambiar. +Object.preventExtensions(empty); +Object.isExtensible(empty); // === false + +// Objetos sellados por definición son no-extendibles. +var sealed = Object.seal({}); +Object.isExtensible(sealed); // === false + +// Objetos congelados también por definición son no-extendibles. +var frozen = Object.freeze({}); +Object.isExtensible(frozen); // === false +</pre> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el argumento pasado a éste método no es un objeto (primitivo), entonces regresará {{jsxref("TypeError")}}. En ES6, un no-objeto pasado como argumento será tratado como si fuera un objeto no-extendible ordinario, simplemente regresa <code>false</code>.</p> + +<pre class="brush: js">Object.isExtensible(1); +// TypeError: 1 is not an object (ES5 code) + +Object.isExtensible(1); +// false (ES6 code) +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.13', 'Object.isExtensible')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementada en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.isextensible', 'Object.isExtensible')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("6")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5.1")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporote básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Reflect.isExtensible()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/isfrozen/index.html b/files/es/web/javascript/reference/global_objects/object/isfrozen/index.html new file mode 100644 index 0000000000..9a2bc2ee94 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/isfrozen/index.html @@ -0,0 +1,190 @@ +--- +title: Object.isFrozen() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/isFrozen +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Objeto + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.isFrozen()</strong></code> determina si un objeto está <em>congelado</em>.</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="syntaxbox"><code>Object.isFrozen(<var>obj</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto a ser revisado.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Un objeto está congelado si y solo si no es {{jsxref("Object.isExtensible()", "extendible", "", 1)}}, todas sus propiedades son no-configurables, y todos los datos de sus propiedades no tienen capacidad de escritura.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">// Un objeto nuevo es extendible, así que no está congelado. +Object.isFrozen({}); // === false + +// Un objeto vacio el cuál no es extendible está congelado vacuamente. +var vacuouslyFrozen = Object.preventExtensions({}); +Object.isFrozen(vacuouslyFrozen); // === true + +// Un objeto nuevo con una propiedad es tabién extendible, ergo no congelado. +var oneProp = { p: 42 }; +Object.isFrozen(oneProp); // === false + +// Prevenir la extensión de un objeto no lo congela. +// porque la propiedad sigue teniendo capacidad de configuración (y capacidad de escritura). +Object.preventExtensions(oneProp); +Object.isFrozen(oneProp); // === false + +// ...pero eliminar la propiedad congela el objeto vacuamente. +delete oneProp.p; +Object.isFrozen(oneProp); // === true + +// Un ojbeto no-extendible con una propiedad sin capacidad de escritura pero si con capacidad de configuración no está congelado. +var nonWritable = { e: 'plep' }; +Object.preventExtensions(nonWritable); +Object.defineProperty(nonWritable, 'e', { writable: false }); // Le quita la capacidad de escritura. +Object.isFrozen(nonWritable); // === false + +// Quitarle la capacidad de configuración a una propiedad congela el objeto. +Object.defineProperty(nonWritable, 'e', { configurable: false }); // le quita la capacidad de configuración. +Object.isFrozen(nonWritable); // === true + +// Un objeto no-extendible con una propiedad sin capacidad de configuración pero con capacidad de escritura no congela a dicho objeto. +var nonConfigurable = { release: 'the kraken!' }; +Object.preventExtensions(nonConfigurable); +Object.defineProperty(nonConfigurable, 'release', { configurable: false }); +Object.isFrozen(nonConfigurable); // === false + +// Quitarle la capacidad de configuración a esa propiedad congela el objeto. +Object.defineProperty(nonConfigurable, 'release', { writable: false }); +Object.isFrozen(nonConfigurable); // === true + +// A non-extensible object with a configurable accessor property isn't frozen. +var accessor = { get food() { return 'yum'; } }; +Object.preventExtensions(accessor); +Object.isFrozen(accessor); // === false + +// ...but make that property non-configurable and it becomes frozen. +Object.defineProperty(accessor, 'food', { configurable: false }); +Object.isFrozen(accessor); // === true + +// But the easiest way for an object to be frozen is if Object.freeze has been called on it. +var frozen = { 1: 81 }; +Object.isFrozen(frozen); // === false +Object.freeze(frozen); +Object.isFrozen(frozen); // === true + +// By definition, a frozen object is non-extensible. +Object.isExtensible(frozen); // === false + +// Also by definition, a frozen object is sealed. +Object.isSealed(frozen); // === true +</pre> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el argumento pasado a éste método no es un objeto (primitivo), entonces causará un {{jsxref("TypeError")}}. En ES6, un no-objeto pasado como argumento será tratado como si fuera un objeto ordinario congelado, simplemente regresa <code>true</code>.</p> + +<pre class="brush: js">Object.isFrozen(1); +// TypeError: 1 is not an object (ES5 code) + +Object.isFrozen(1); +// true (ES6 code) +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> + <p>Definición inicial. Implementada en JavaScript 1.8.5.</p> + </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristicas</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("6")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5.1")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristicas</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/isprototypeof/index.html b/files/es/web/javascript/reference/global_objects/object/isprototypeof/index.html new file mode 100644 index 0000000000..8275ebafac --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/isprototypeof/index.html @@ -0,0 +1,158 @@ +--- +title: Object.prototype.isPrototypeOf() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/isPrototypeOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>isPrototypeOf()</strong></code> comprueba si un objeto se encuentra en la cadena de prototipado de otro.</p> + +<div class="note"> +<p><strong>Nota:</strong> <code>isPrototypeOf</code> difiere del operador {{jsxref("Operators/instanceof", "instanceof")}}. En la expresión "<code>object instanceof AFunction</code>", la cadena de prototipado de <code>object</code> es comprobada contra <code>AFunction.prototype</code>, no contra la propia <code>AFunction</code>.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code><var>prototypeObj</var>.isPrototypeOf(<var>obj</var>)</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>prototypeObj</code></dt> + <dd>Un objeto para ver comprobado contra cada vínculo en la cadena de prototipado del argumento <strong>object</strong>.</dd> + <dt><code>object</code></dt> + <dd>El object sobre cuya cadena de prototipado se realizará la búsqueda.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>El método <code>isPrototypeOf</code> permite comprobar si un objetyo existe o no en la cadena de prototipado de otro.</p> + +<p>Por ejemplo, considerese la siguiente cadena de prototipado:</p> + +<pre class="brush: js">function Fee() { + // ... +} + +function Fi() { + // ... +} +Fi.prototype = new Fee(); + +function Fo() { + // ... +} +Fo.prototype = new Fi(); + +function Fum() { + // ... +} +Fum.prototype = new Fo(); +</pre> + +<p>Al final de la secuencia, si se instanci <code>Fum</code> y se necesita verificar si el prototipo de <code>Fi</code> existe en la cadena de prototipado de <code>Fum</code> prototype chain, puede hacerse esto:</p> + +<pre class="brush: js">var fum = new Fum(); +// ... + +if (Fi.prototype.isPrototypeOf(fum)) { + // do something safe +} +</pre> + +<p>Esto, junto con el operador {{jsxref("Operators/instanceof", "instanceof")}} resulta especialmente útil si se tiene código que sólo puede operar cuando se trata de objetos descendientes de una cadena de prototipado específica, p.e., para garantizar que ciertos métodos o propiedades estén presentes en dichos objetos.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li> + <div>{{jsxref("Object.setPrototypeOf()")}}</div> + </li> + <li>{{jsxref("Object.prototype.__proto__")}} </li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/issealed/index.html b/files/es/web/javascript/reference/global_objects/object/issealed/index.html new file mode 100644 index 0000000000..c28437561a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/issealed/index.html @@ -0,0 +1,140 @@ +--- +title: Object.isSealed() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/isSealed +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Objeto + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.isSealed()</strong></code> si el objeto está sellado.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-issealed.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Object.isSealed(<var>obj</var>)</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto que debe ser verificado.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un {{jsxref("Boolean")}} indicando si el objeto dado está sellado.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>Devuelve <code>true</code> si el objeto está sellado, de lo contrario devuelve <code>false</code>. Un objeto está sellado si no es {{jsxref("Object.isExtensible", "extensible", "", 1)}} y si todas sus propiedades no se pueden configurar y por lo tanto no removibles (pero no necesariamente no modificables).</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">// Los objetos no están sellados por defecto +var empty = {}; +Object.isSealed(empty); // === false + +// Si haces un objeto vacío no extendible, +// está vacíamente sellado +Object.preventExtensions(empty); +Object.isSealed(empty); // === true + +// Lo mismo no es vedad sobre un objeto no vacío, +// a menos que sus propiedades son todas no configurables. +var hasProp = { fee: 'fie foe fum' }; +Object.preventExtensions(hasProp); +Object.isSealed(hasProp); // === false + +// Pero hazlas todas no configurables +// y el objeto se vuelve sellado. +Object.defineProperty(hasProp, 'fee', { + configurable: false +}); +Object.isSealed(hasProp); // === true + +// La manerá más facil de sellar un objeto, por supuesto, +// es Object.seal +var sealed = {}; +Object.seal(sealed); +Object.isSealed(sealed); // === true + +// Un objeto sellado es, por definición, no extendible. +Object.isExtensible(sealed); // === false + +// Un objeto sellado puodría estar congelado, +// pero no tiene que ser. +Object.isFrozen(sealed); // === true +// (Todas las propiedades también no modificables) + +var s2 = Object.seal({ p: 3 }); +Object.isFrozen(s2); // === false +// ('p' todavía es modificable) + +var s3 = Object.seal({ get p() { return 0; } }); +Object.isFrozen(s3); // === true +// (solo la configurabilidad es importante para las propiedades de acceso) +</pre> + +<h2 id="Notes">Notes</h2> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">En ES5, si el argumento de este método no es un objeto (primitivo), entonces causará un </span></font></code>{{jsxref("TypeError")}}. En ES2015, un argumento que no sea un objeto será tratado como si fuera un objeto sellado ordinario, simplemente devuelve <code>true</code>.</p> + +<pre class="brush: js">Object.isSealed(1); +// TypeError: 1 no es un objeto (ES5 code) + +Object.isSealed(1); +// true (ES2015 code) +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementada en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.isSealed")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/keys/index.html b/files/es/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..d6bd068f2f --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,156 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/keys +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +<div>{{JSRef("Global_Objects", "Object")}}</div> + +<h2 id="Resumen">Resumen</h2> + +<p>El método <code>Object.keys()</code> devuelve un array de las propiedades <strong><code>names</code> </strong>de un objeto, en el mismo orden como se obtienen en un loop normal</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><code>Object.keys(<var>obj</var>)</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto cuyas propiedades enumerables serán devueltas.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un array de strings que representan toda las propiedades del objeto</p> + +<h2 id="Descripción">Descripción</h2> + +<p><code>Object.keys</code> devuelve un array cuyos elementos son strings correspondientes a las propiedades enumerables que se encuentran directamente en el object. El orden de las propiedades es el mismo que se proporciona al iterar manualmente sobre las propiedades del objeto.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js notranslate">var arr = ['a', 'b', 'c']; +console.log(Object.keys(arr)); // console: ['0', '1', '2'] + +// arreglo como objeto +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.keys(obj)); // console: ['0', '1', '2'] + +// arreglo como objeto con nombres ordenados aleatoriamente +var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.keys(an_obj)); // console: ['2', '7', '100'] + +// getFoo es una propiedad no enumerable +var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); +my_obj.foo = 1; + +console.log(Object.keys(my_obj)); // console: ['foo'] +</pre> + +<p>Si quieres todas las propiedades, incluso las no enumerables, mira {{jsxref("Object.getOwnPropertyNames()")}}.</p> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el argumento para este método no es un objeto (uno primitivo), causará un {{jsxref("Global_Objects/TypeError", "TypeError")}}. En ES2015, un argumento no-objeto será coaccionado hacia un objeto.</p> + +<pre class="brush: js notranslate">> Object.keys("foo") +// TypeError: "foo" is not an object (ES5) + +> Object.keys("foo") +// ["0", "1", "2"] (ES2015)</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Para añadir soporte <code>Object.keys</code> en entornos más antiguos que no lo soportan de forma nativa, copia el siguiente fragmento:</p> + +<pre class="brush: js notranslate">// De https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys +if (!Object.keys) { + Object.keys = (function() { + 'use strict'; + var hasOwnProperty = Object.prototype.hasOwnProperty, + hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), + dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ], + dontEnumsLength = dontEnums.length; + + return function(obj) { + if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { + throw new TypeError('Object.keys called on non-object'); + } + + var result = [], prop, i; + + for (prop in obj) { + if (hasOwnProperty.call(obj, prop)) { + result.push(prop); + } + } + + if (hasDontEnumBug) { + for (i = 0; i < dontEnumsLength; i++) { + if (hasOwnProperty.call(obj, dontEnums[i])) { + result.push(dontEnums[i]); + } + } + } + return result; + }; + }()); +} +</pre> + +<p>Ten en cuenta que el código anterior incluye claves no-enumerables en IE7 (y quizás IE8), al pasar en un objeto desde una ventana diferente.</p> + +<p>Para un simple Polyfill del Navegador, mira <a href="http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html">Javascript - Compatibilidad de Object.keys en Navegadores</a>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentarios</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementado en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.keys', 'Object.keys')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{Compat("javascript.builtins.Object.keys")}}</div> + + + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Propiedades de enumerabilidad y pertenencia</a></li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Object.values()")}}</li> + <li>{{jsxref("Object.entries()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/es/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..50f51214a8 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,176 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/preventExtensions +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.preventExtensions()</strong></code> previene que nuevas propiedades sean agregadas a un objeto (p.e. previene la extensión futuras al objeto).</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code>Object.preventExtensions(<var>obj</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto que debería hacerse inextendible.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Un objeto es extendible si propiedades nuevas pueden ser agregadas a este. Object.preventExtensions() marca un objecto como no extendible, así nunca más tendrá propiedades más allá de las tenía en el momento en que fue marcado como no extendible. Note que las propiedades de un objeto no-extendible, en general, aún pueden ser eliminadas. Los intentos de agregar propiedades nuevas a un objeto no-extendible fallarán, ya sea de manera silenciosa o arrojando una excepción {{jsxref("TypeError")}} (comunmente, pero no de manera exclusiva, en {{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}}).</p> + +<p><code>Object.preventExtensions()</code> solo previene la adición de propiedades propias. Las propiedades aún pueden ser agregadas a object.prototype. Sin embargo, llamar <code>Object.preventExtensions()</code> sobre un objeto tambien prevendrá extensiones sobre la propiedad {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}}.</p> + +<p>Si hay una manera de cambiar un objeto extendible a uno no-extendible, hay una manera de hacer lo opuesto en ECMAScript 5.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">// Object.preventExtensions regresa el objeto hecho no-extendible. +var obj = {}; +var obj2 = Object.preventExtensions(obj); +obj === obj2; // true + +// Los Objetos son extendibles por defecto. +var empty = {}; +Object.isExtensible(empty); // === true + +// ...pero pueden ser cambiados. +Object.preventExtensions(empty); +Object.isExtensible(empty); // === false + +// Object.defineProperty arroja una excepción cuando se agrega +// una propiedad nueva a un objeto no-extendible. +var nonExtensible = { removable: true }; +Object.preventExtensions(nonExtensible); +Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // arroja TypeError + +// En modo estricto, tratar de agregar propiedades nuevas +// a un objeto no-extensible arroja una excepción TypeError. +function fail() { + 'use strict'; + nonExtensible.newProperty = 'FAIL'; // arroja TypeError +} +fail(); + +// EXTENSION (solo funciona en motores que soporten __proto__ +// (el cual esta obsoleto. Usar Object.getPrototypeOf en su lugar)): +// La propiedad prototype de un objeto no-extendible es inmutable. +var fixed = Object.preventExtensions({}); +fixed.__proto__ = { oh: 'hai' }; // arroja TypeError +</pre> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el argumento pasado a este método no es un objeto (primitivo), entonces causará un {{jsxref("TypeError")}}. En ES6, un argumento no-objeto será tratado como si fuera un objeto ordinario no-extendible, simplemente lo regresa.</p> + +<pre class="brush: js">Object.preventExtensions(1); +// TypeError: 1 is not an object (ES5 code) + +Object.preventExtensions(1); +// 1 (ES6 code) +</pre> + +<h2 id="Especificación">Especificación</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementada en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("6")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5.1")}}</td> + </tr> + <tr> + <td>Comportamiento en ES6 para un no-objeto pasado como argumento</td> + <td>{{CompatChrome("44")}}</td> + <td>{{CompatGeckoDesktop("35.0")}}</td> + <td>{{CompatIE("11")}}</td> + <td>{{CompatOpera("31")}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Comportamiento en ES6 para no-objetos pasados como argumentos</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("35.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Reflect.preventExtensions()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/propertyisenumerable/index.html b/files/es/web/javascript/reference/global_objects/object/propertyisenumerable/index.html new file mode 100644 index 0000000000..b2ede9dd60 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/propertyisenumerable/index.html @@ -0,0 +1,185 @@ +--- +title: Object.prototype.propertyIsEnumerable() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/propertyIsEnumerable +tags: + - JavaScript + - Objecto + - Property + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>propertyIsEnumerable()</strong></code> regresa un Boleano indicando si la propiedad especificada es enumerable.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code><var>obj</var>.propertyIsEnumerable(<var>prop</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>Nombre de la propiedad a probar.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Todos los objetos tienen un método <code>propertyIsEnumerable</code>. Este método puede determinar si la propiedad especificada en el objeto puede ser enumerada por un ciclo {{jsxref("Statements/for...in", "for...in")}}, con la excepción de propiedades heredadas a través de prototype. Si el objeto no tiene la propiedad especificada, este método regresa un valor <code>false</code>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="Uso_básico_de_propertyIsEnumerable">Uso básico de <code>propertyIsEnumerable</code></h3> + +<p>El siguiente ejemplo muestra el uso de <code>propertyIsEnumerable</code> en objetos y arrays:</p> + +<pre class="brush: js">var o = {}; +var a = []; +o.prop = 'es enumerable'; +a[0] = 'es enumerable'; + +o.propertyIsEnumerable('prop'); // regresa true +a.propertyIsEnumerable(0); // regresa true +</pre> + +<h3 id="Definidas_por_usuario_vs_predefinidas">Definidas por usuario vs predefinidas</h3> + +<p>El siguiente ejemplo demuestra la enumerabilidad de las propiedades definidas por el usuario contra las predefinidas:</p> + +<pre class="brush: js">var a = ['es enumerable']; + +a.propertyIsEnumerable(0); // regresa true +a.propertyIsEnumerable('length'); // regresa false + +Math.propertyIsEnumerable('random'); // regresa false +this.propertyIsEnumerable('Math'); // regresa false +</pre> + +<h3 id="Directa_vs_heredadas">Directa vs heredadas</h3> + +<pre class="brush: js">var a = []; +a.propertyIsEnumerable('constructor'); // regresa false + +function primerConstructor() { + this.propiedad = 'no es enumerable'; +} + +primerConstructor.prototype.primerMetodo = function() {}; + +function segundoConstructor() { + this.metodo = function() { return 'es enumerable'; }; +} + +secondConstructor.prototype = new primerConstructor; +secondConstructor.prototype.constructor = segundoConstructor; + +var o = new segundoConstructor(); +o.propiedadArbitraria = 'is enumerable'; + +o.propertyIsEnumerable('propiedadArbitraria '); // regresa true +o.propertyIsEnumerable('metodo'); // regresa true +o.propertyIsEnumerable('propiedad'); // regresa false + +o.propiedad = 'es enumerable'; + +o.propertyIsEnumerable('propiedad'); // regresa true + +// Regresan false por estar en el prototipo el cual no es +// considerado por propertyIsEnumerable (a pesar de que las dos ultimas son +// iterables con un for-in) +o.propertyIsEnumerable('prototype'); // regresa false (como en JS 1.8.1/FF3.6) +o.propertyIsEnumerable('constructor'); // regresa false +o.propertyIsEnumerable('firstMethod'); // regresa false +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estatus</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.7', 'Object.prototype.propertyIsEnumerable')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.propertyisenumerable', 'Object.prototype.propertyIsEnumerable')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Notas_específicas_para_Gecko">Notas específicas para Gecko</h2> + +<p>Al inicio de JavaScript 1.8.1 (in Firefox 3.6), <code>propertyIsEnumerable('prototype')</code> regresa <code>false</code> en lugar de <code>true</code>; esto hace que el resultado cumpla con la especificación de ECMAScript 5.</p> + +<h2 id="Véase_también">Véase también</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/proto/index.html b/files/es/web/javascript/reference/global_objects/object/proto/index.html new file mode 100644 index 0000000000..24055ac261 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/proto/index.html @@ -0,0 +1,128 @@ +--- +title: Object.prototype.__proto__ +slug: Web/JavaScript/Referencia/Objetos_globales/Object/proto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/proto +--- +<div class="warning"> +<p><strong>Advertencia:</strong> Cambiar la propiedad <code>[[Prototype]]</code> de un objeto es, por como los navegadores modernos optimizan las propiedades de acceso, una operación muy lenta en <strong><em>todos</em></strong> los navegadores y motores JavaScript. Los efectos en el rendimiento de alterar la herencia son muchos y delicados, y no se limita simplemente al tiempo que necesita la asignación <code>obj.__proto__ = ...</code> sentencia, sin embargo afecta a <strong><em>cualquier</em></strong> código que tiene acceso a <strong><em>cualquier</em></strong> objeto cuya propiedad <code>[[Prototype]]</code> ha sido alterada, por lo que se debe de tener mucho cuidado.</p> + +<p>Si el rendimiento en tu aplicación es necesario, deberías evitar modificar la propiedad <code>[[Prototype]]</code> de un objeto. En su lugar, crea un objecto nuevo con la propiedad <code>[[Prototype]]</code> deseada usando {{jsxref("Object.create()")}}.</p> +</div> + +<div class="warning"> +<p><strong>Advertencia:</strong> Mientras <code>Object.prototype.__proto__</code> es soportado hoy día por la mayoría de navegadores, su existencia y comportamiento exacto solo ha sido estandarizado en la especificación ECMAScript 6 como una característica de legado y para asegurar la compatibilidad entre los navegadores web. Para tener un mejor soporte, es recomendable que se utilice {{jsxref("Object.getPrototypeOf()")}} para obtener el prototipo de un objeto.</p> +</div> + +<div>{{JSRef}}</div> + +<p>La propiedad <code>__proto__</code> de {{jsxref("Object.prototype")}} es una propiedad llamada de acceso (una función getter y también función setter) que provee acceso al interior de <code>[[Prototype]]</code> (ya sea un objeto o {{jsxref("Global_Objects/null", "null")}}) del objeto a través del cual se accede a ella.</p> + +<p>El uso de la propiedad <code>__proto__</code> es polémico actualmente, y está rechazado. Originalmente, nunca fué incluído en la especificación de EcmaScript, pero los navegadores modernos decidieron implementarla de todas maneras. Sólo actualmente, <code>la propiedad __proto__</code> ha sido estandarizada en la especificación del lenguaje ECMAScript 6, para asegurar la compatibilidad entre navegadores, por lo tanto, esta será soportada en el futuro. Actualmente está obsoleta en favor de {{jsxref("Object.getPrototypeOf")}}/{{jsxref("Reflect.getPrototypeOf")}} y {{jsxref("Object.setPrototypeOf")}}/{{jsxref("Reflect.setPrototypeOf")}} (aunque todavía establecer el <code>[[Prototype]]</code> de un objeto es una operación muy lenta, por lo que si nos preocupa el rendimiento, debemos de evitarlo).</p> + +<p>La propiedad <code>__proto__</code> puede ser usada también en un objeto definido de forma literal, para establecer el <code>[[Prototype]]</code> en la creación de este, como alternativa a {{jsxref("Object.create()")}}. Ver: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Síntaxis">Síntaxis</h2> + +<pre class="brush: js">var shape = {}; +var circle = new Circle(); + +// Establecer el objeto prototype. +// OBSOLETO. Esto es solo un ejemplo. NO HACER ESTO en código real. +shape.__proto__ = circle; + +// Obtener el objeto prototype +console.log(shape.__proto__ === circle); // true +</pre> + +<p>Nota: esto es, dos guiones bajos, seguidos de cinco carácteres "proto", seguido de dos guiones bajos mas.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>La función getter <code>__proto__</code>el valor interno del <code>[[Prototype]]</code> de un objeto. Para objetos creados usando un objeto literal, el valor es {{jsxref("Object.prototype")}}. Para objetos creados usando literales de array, este valor es {{jsxref("Array.prototype")}}. Para funciones, este valor {{jsxref("Function.prototype")}}. Para objetos creados utilizando el operador new fun, donde <strong>fun</strong> es una función constructora incluída en JavaScript ({{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("String")}}, etcétera—incluyendo nuevos contrusctores conforme JavaScript evoluciona), este valor es <code>fun.prototype</code>. (Esto es, si el constructor no devuelve un objeto de forma explícita, o el <code>fun.prototype</code> ha sido reasignado desde que la instancia fué creada).</p> + +<p>El <code>__proto__</code> setter la mutación del objeto <code>[[Prototype]]</code> de un objeto. El objeto debe ser extensible según {{jsxref("Object.isExtensible()")}}: si no, un {{jsxref("Global_Objects/TypeError", "TypeError")}} es lanzado. El valor proveído debe ser un objeto o {{jsxref("Global_Objects/null", "null")}}. Provetendo otro tipo de valor no hará nada.</p> + +<p>Para entender como los prototipos son usados para herencia, ver el artículo <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a>.</p> + +<p>La propiedad <code>__proto__</code> es una simple propiedad de acceso a {{jsxref("Object.prototype")}} que consiste en una función getter y setter. Un acceso a la propiedad <code>__proto__</code> que eventualmente consulta {{jsxref("Object.prototype")}} encontrará esta propiedad, pero un acceso que no consulta {{jsxref("Object.prototype")}} no lo encontrará. Si alguna otra propiedad <code>__proto__</code> es encontrada antes {{jsxref("Object.prototype")}} es consultada, esta propiedad sera ocultada por la encontrada en {{jsxref("Object.prototype")}}.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciones</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Incluída en el anexo (normativa) para características de legado ECMAScript para navegadores web (observar que la especificación de codificación es lo que ya está en las implementaciones).</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("11")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Caracteristica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Notas_de_compatibilidad">Notas de compatibilidad</h2> + +<p>Mientras la especificación ECMAScript 2015 (ES6) dicta que el soporte para <code>__proto__</code> es requerido <em>solo</em> para navegadores web (a pesar de ser normativo), otros medios pueden soportarlo por uso de legado.</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/seal/index.html b/files/es/web/javascript/reference/global_objects/object/seal/index.html new file mode 100644 index 0000000000..42c89175a3 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/seal/index.html @@ -0,0 +1,167 @@ +--- +title: Object.seal() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/seal +translation_of: Web/JavaScript/Reference/Global_Objects/Object/seal +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.seal()</strong></code> sella un objeto, previniendo que puedan añadirse nuevas propiedades al mismo, y marcando todas las propiedades existentes como no-configurables. Los valores de las propiedades presentes permanecen pudiendo cambiarse en tanto en cuanto dichas propiedades sean de escritura.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code>Object.seal(<var>obj</var>)</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto que ha de ser sellado.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Por defecto, los objetos son {{jsxref("Object.isExtensible()", "extensibles", "", 1)}} (pueden añadirse nuevas propiedades a los mismos). Sellar un objeto previene que nuevas propiedades puedan ser añadidas y marca todas las propiedades existentes como no-configurables. Esto tiene el efecto de hacer fijo e inmutable el juego de propiedades del objeto. Al hacer todas las propiedades no-configurables previene también que se puedan convertir propiedades de datos en propiedades de acceso y viceversa, pero no evita que los valores de las propiedades de datos puedan ser modificados. Intentar eliminar o añadir propiedades a un objeto sellado, o convertir una propiedad de datos en una propiedad de acceso fallará, bien silenciadamente o bien produciendo un {{jsxref("TypeError")}} (más frecuentemente, aunque no exclusivamente, con código en {{jsxref("Strict_mode", "modo estricto", "", 1)}}).</p> + +<p>La cadena de prototiado permanece inalterada. No obstante, la propiedad {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} es también sellada.</p> + +<p>Retorna una referencia al Objeto pasado.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var obj = { + prop: function() {}, + foo: 'bar' +}; + +// Pueden añadirse nuevas propiedades, propiedades existentes pueden cambiarse o eliminarse. +obj.foo = 'baz'; +obj.lumpy = 'woof'; +delete obj.prop; + +var o = Object.seal(obj); + +o === obj; // true +Object.isSealed(obj); // === true + +// Sigue permitido modificar valores de propiedades en un objeto sellado. +obj.foo = 'quux'; + +// Pero no puedes convertir propiedades de datos en propiedades de acceso, ni viveversa +Object.defineProperty(obj, 'foo', { get: function() { return 'g'; } }); // produce un TypeError + +// Ahora, cualquier cambio que no sea modificar valores de propiedades fallará +obj.quaxxor = 'the friendly duck'; // silenciosamente, no añadirá la propiedad +delete obj.foo; // silenciosamente, no eliminará la propiedad + +// ...y en modo estricto esos intentos producirán TypeErrors. +function fail() { + 'use strict'; + delete obj.foo; // genera un TypeError + obj.sparky = 'arf'; // genera un TypeError +} +fail(); + +// Intentar añadir propiedades mediante Object.defineProperty también fallará. +Object.defineProperty(obj, 'ohai', { value: 17 }); // genera un TypeError +Object.defineProperty(obj, 'foo', { value: 'eit' }); // cambia el valor exisitente +</pre> + +<h2 id="Notas">Notas</h2> + +<p>En ES5, si el argumento de este método no es un objeto (una primitiva), se generará un {{jsxref("TypeError")}}. En ES6, un argumento no-objeto será tratado como si se sellase un objeto ordinario, símplemente retornándolo.</p> + +<pre class="brush: js">Object.seal(1); +// TypeError: 1 no es un objeto (código ES5) + +Object.seal(1); +// 1 (código ES6) +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Observaciones</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definición inicial. Implementado en JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestación</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatChrome("6")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5.1")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Prestiación</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/setprototypeof/index.html b/files/es/web/javascript/reference/global_objects/object/setprototypeof/index.html new file mode 100644 index 0000000000..ff32fc5738 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/setprototypeof/index.html @@ -0,0 +1,237 @@ +--- +title: Object.setPrototypeOf() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/setPrototypeOf +tags: + - ECMAScript6 + - Experimental + - JavaScript + - Método(2) + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf +--- +<p>{{JSRef}}</p> + +<p>El método <code><strong>Object.setPrototypeOf()</strong></code> establece el prototipo (p.e., la propiedad interna <code>[[Prototype]]</code>) de un objeto especificado a otro objeto o sino establece {{jsxref("null")}}.</p> + +<div class="warning"> +<p><strong>Adverdencia:</strong> Cambiar la propiedad <code>[[Prototype]]</code> de un objeto, debido a la naturaleza de la optimización del acceso a propiedades de los motores modernos de JavaScript, es una operación bastante lenta, en todo <strong><em>todo</em></strong> navegador y motor de JavaScript. Los efectos sobre el rendimiento al alterar la herencia son sutiles y vastos., y no están limitados a simplemente el tiempo gastado en la sentencia <code>obj.__proto___ = ...</code>, but may extend to <strong><em>any</em></strong> code that has access to <strong><em>any</em></strong> object whose <code>[[Prototype]]</code> has been altered. If you care about performance you should avoid setting the <code>[[Prototype]]</code> of an object. Instead, create a new object with the desired <code>[[Prototype]]</code> using {{jsxref("Object.create()")}}.</p> +</div> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code>Object.setPrototypeOf(<var>obj</var>, <var>prototype</var>);</code></pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>El objeto al que se ha de establecer el prototipo.</dd> + <dt><code>prototype</code></dt> + <dd>El nuevo prototipo del objeto, (un objeto o {{jsxref("null")}}).</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Arroja una excepción del tipo {{jsxref("TypeError")}} si el objeto cuyo <code>[[Prototype]]</code> se va a modificar no es extensible de acuerdo con {{jsxref("Object.isExtensible()")}}. No hace nada si el parametro <code>prototype</code> no es un objeto o {{jsxref("null")}} (p.e., número, cadena, booleano, o {{jsxref("undefined")}}). De cualquier otra forma, este método cambia la propiedad <code>[[Prototype]]</code> del <code>obj</code> al valor nuevo.</p> + +<p><code>Object.setPrototypeOf()</code> está en el último borrador del estandar ECMAScript6. Es considerado generalmente la manera adecuada de establecer el prototipo de un objeto, contra la propiedad más controversial {{jsxref("Object.prototype.__proto__")}}.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var dict = Object.setPrototypeOf({}, null); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Utilizando la vieja propiedad {{jsxref("Object.prototype.__proto__")}}, podemos definir facilmente <code>Object.setPrototypeOf</code> si aún no está disponible:</p> + +<pre class="brush: js">// Solo funciona en Chrome y FirefoxOnly works in Chrome y FireFox, no funciona en IE: +Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) { + obj.__proto__ = proto; + return obj; +} +</pre> + +<h2 id="Agregando_cadenas_de_prototipo">Agregando cadenas de prototipo</h2> + +<p>Una combinación de <code>Object.getPrototypeOf()</code> y {{jsxref("Object.proto", "Object.prototype.__proto__")}} permite agregar una nueva cadena de prototipos al nuevo prototipo del objeto.</p> + +<pre class="brush: js">/** +*** Object.appendChain(@object, @prototype) +* +* Agrega el primer prototipo no-nativo de una cadena a un nuevo prototipo. +* Retorna @object (si es Primitivo (Primitive value) será transoformado a Objeto). +* +*** Object.appendChain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body") +*** Object.appendChain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body") +* +* Agrega el primer prototipo no-nativo de una cadena a la Function.prototype nativa del objeto, luego agrega una +* ueva Function(["@arg"(s)], "@function_body") a la cadena. +* Retorna la función. +* +**/ + +Object.appendChain = function(oChain, oProto) { + if (arguments.length < 2) { + throw new TypeError('Object.appendChain - Not enough arguments'); + } + if (typeof oProto === 'number' || typeof oProto === 'boolean') { + throw new TypeError('second argument to Object.appendChain must be an object or a string'); + } + + var oNewProto = oProto, + oReturn = o2nd = oLast = oChain instanceof this ? oChain : new oChain.constructor(oChain); + + for (var o1st = this.getPrototypeOf(o2nd); + o1st !== Object.prototype && o1st !== Function.prototype; + o1st = this.getPrototypeOf(o2nd) + ) { + o2nd = o1st; + } + + if (oProto.constructor === String) { + oNewProto = Function.prototype; + oReturn = Function.apply(null, Array.prototype.slice.call(arguments, 1)); + this.setPrototypeOf(oReturn, oLast); + } + + this.setPrototypeOf(o2nd, oNewProto); + return oReturn; +} +</pre> + +<h3 id="Uso">Uso</h3> + +<h4 id="Primer_ejemplo_Agregar_una_cadena_a_un_prototipo">Primer ejemplo: Agregar una cadena a un prototipo</h4> + +<pre class="brush: js">function Mammal() { + this.isMammal = 'yes'; +} + +function MammalSpecies(sMammalSpecies) { + this.species = sMammalSpecies; +} + +MammalSpecies.prototype = new Mammal(); +MammalSpecies.prototype.constructor = MammalSpecies; + +var oCat = new MammalSpecies('Felis'); + +console.log(oCat.isMammal); // 'yes' + +function Animal() { + this.breathing = 'yes'; +} + +Object.appendChain(oCat, new Animal()); + +console.log(oCat.breathing); // 'yes' +</pre> + +<h4 id="Segundo_ejemplo_Transofrmando_un_valor_Primitivo_en_una_instancia_de_su_constructor_y_agregar_su_cadena_al_prototipo">Segundo ejemplo: Transofrmando un valor Primitivo en una instancia de su constructor y agregar su cadena al prototipo</h4> + +<pre class="brush: js">function Symbol() { + this.isSymbol = 'yes'; +} + +var nPrime = 17; + +console.log(typeof nPrime); // 'number' + +var oPrime = Object.appendChain(nPrime, new Symbol()); + +console.log(oPrime); // '17' +console.log(oPrime.isSymbol); // 'yes' +console.log(typeof oPrime); // 'object' +</pre> + +<h4 id="Tercer_ejemplo_Agregando_una_cadena_a_la_Function.prototype_de_un_objeto_y_agregando_una_nueva_función_a_la_cadena">Tercer ejemplo: Agregando una cadena a la Function.prototype de un objeto y agregando una nueva función a la cadena</h4> + +<pre class="brush: js">function Person(sName) { + this.identity = sName; +} + +var george = Object.appendChain(new Person('George'), + 'console.log("Hello guys!!");'); + +console.log(george.identity); // 'George' +george(); // 'Hello guys!!' +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.setprototypeof', 'Object.setProtoypeOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("34")}}</td> + <td>{{CompatGeckoDesktop("31")}}</td> + <td>{{CompatIE("11")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("31")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Reflect.setPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.__proto__")}} </li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/tolocalestring/index.html b/files/es/web/javascript/reference/global_objects/object/tolocalestring/index.html new file mode 100644 index 0000000000..d0de708b98 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/tolocalestring/index.html @@ -0,0 +1,106 @@ +--- +title: Object.prototype.toLocaleString() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/toLocaleString +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toLocaleString +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>toLocaleString()</strong></code> devuelve un string que representa a un objeto. Este método está pensado para ser redefinido en los objetos derivados, para los propósitos específicos de cada configuración regional.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-tolocalestring.html")}}</div> + + + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><var>objeto</var>.toLocaleString()</pre> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un string que representa al objeto.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>{{jsxref("Object")}}'s <code>toLocaleString</code> devuelve el resultado de llamar a {{jsxref("Object.toString", "toString()")}}.</p> + +<p>Se proporciona esta función para que los objetos dispongan de un método <code>toLocaleString</code> genérico, aunque puede que no todos la utilicen. Véase la lista siguiente.</p> + +<h3 id="Objetos_que_redefinen_toLocaleString">Objetos que redefinen <code>toLocaleString</code></h3> + +<ul> + <li>{{jsxref("Array")}}: {{jsxref("Array.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Number")}}: {{jsxref("Number.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date")}}: {{jsxref("Date.prototype.toLocaleString()")}}</li> + <li>{{jsxref("TypedArray")}}: {{jsxref("TypedArray.prototype.toLocaleString()")}}</li> + <li>{{jsxref("BigInt")}}: {{jsxref("BigInt.prototype.toLocaleString()")}}</li> +</ul> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Redefinición_de_toLocaleString_en_Array">Redefinición de toLocaleString() en Array</h3> + +<p>En los objetos <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code> se puede utilizar <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString">toLocaleString()</a></code> para imprimir los valores del <em>array</em> como un string, con indicadores opcionales de configuración regional (como símbolos de moneda) aplicados.</p> + +<p>Por ejemplo:</p> + +<pre class="brush: js notranslate">const unArray = [4, 7, 10]; + +let preciosEnEuros = unArray.toLocaleString('fr', { style: 'currency', currency: 'EUR'}); +// "4,00 €,7,00 €,10,00 €"</pre> + +<h3 id="Redefinición_de_toLocaleString_para_Date">Redefinición de toLocaleString() para Date</h3> + +<p>En los objetos <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a></code> se usa <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString">toLocaleString()</a></code> para imprimir fechas en un formato adecuado a la configuración regional.</p> + +<p>Por ejemplo:</p> + +<pre class="brush: js notranslate">const unaFecha = new Date(Date.now()); +// <span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox"><span class="objectTitle">"</span>2020-07-07T19:51:44.046Z<span class="Date">" + +</span></span></span></span></span>let fechaAleman = unaFecha.toLocaleString('de'); +// "7.7.2020, 21:55:22" + +var fechaFrances= unaFecha.toLocaleString('fr'); +//"07/07/2020 à 21:55:22"</pre> + +<h3 id="Redefinición_de_toLocaleString_para_Number">Redefinición de toLocaleString() para Number</h3> + +<p>En los objetos <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a></code> se usa <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString">toLocaleString()</a></code> para imprimir números de forma adecuada a la configuración regional, p. ej. para usar los separadores de miles correctos.</p> + +<p>Por ejemplo:</p> + +<pre class="brush: js notranslate">const unNumero = 2901234564; +// <span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">"2901234564" + +</span></span></span></span>let numeroAleman = unNumero.toLocaleString('de'); +// "2.901.234.564" + +let numeroFrances = unNumero.toLocaleString('fr'); +// "2 901 234 564"</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.tolocalestring', 'Object.prototype.toLocaleString')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + + + +<p>{{Compat("javascript.builtins.Object.toLocaleString")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/tosource/index.html b/files/es/web/javascript/reference/global_objects/object/tosource/index.html new file mode 100644 index 0000000000..713a176b0b --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/tosource/index.html @@ -0,0 +1,126 @@ +--- +title: Object.prototype.toSource() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>El método <strong><code>toSource()</code></strong> regresa una cadena representando el código fuente del objeto.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Object.toSource(); +<var>obj</var>.toSource(); +</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>Una cadena representando el código fuente del objeto.</p> + +<h2 id="Description">Description</h2> + +<p>EL método <code>toSource()</code> regresa los siguientes valores:</p> + +<ul> + <li>Para el objeto incorporado {{jsxref("Object")}}, <code>toSource()</code> regresa la siguiente cadena indicando que el código fuente no está disponible: + + <pre class="brush: js">function Object() { + [native code] +} +</pre> + </li> + <li>Para instancias de {{jsxref("Object")}}, <code>toSource()</code> regresa una cadena representando el código fuente.</li> +</ul> + +<p>Puedes llamar el método <code>toSource()</code> durante el depurado para examinar el contenido de un objeto.</p> + +<h3 id="Sobreescribir_el_método_toSource()"><code><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="background-color: #333333;">Sobreescribir el método </span></font>toSource()</code></h3> + +<p>Es seguro para los objetos sobreescribir el método <strong>toSource()</strong><strong>.</strong> Por ejemplo:</p> + +<pre class="brush: js">function Person(name) { + this.name = name; +} + +Person.prototype.toSource = function Person_toSource() { + return 'new Person(' + uneval(this.name) + ')'; +}; + +console.log(new Person('Joe').toSource()); // ---> nueva Person("Joe") +</pre> + +<h3 id="Métodos_de_toSource()_incorporados">Métodos de <code>toSource()</code> incorporados</h3> + +<p>Cada tipo fundamental de JavaScript tiene su propio método <code>toSource()</code>. Éstos objetos son:</p> + +<ul> + <li>{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("Array")}} object.</li> + <li>{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("Boolean")}} object.</li> + <li>{{jsxref("Date.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("Date")}} object.</li> + <li>{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("Function")}} object.</li> + <li>{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("Number")}} object.</li> + <li>{{jsxref("RegExp.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("RegExp")}} object.</li> + <li>{{jsxref("SIMD.toSource()", "SIMD.%type%.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("SIMD")}} objects.</li> + <li>{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("String")}} object.</li> + <li>{{jsxref("Symbol.prototype.toSource()")}} {{non-standard_inline}} — {{jsxref("Symbol")}} object.</li> + <li><code>Math.toSource()</code> — Regrsa la cadena "Math".</li> +</ul> + +<h3 id="Limitaciones_en_objetos_cíclicos">Limitaciones en objetos cíclicos</h3> + +<p>EN el caso de los objetos que contienen referencia a ellos mismos, por ejemplo, una lista enlazada cíclicamente o un árbol que puede ser atravesado en ambas formas, <code>toSource()</code> no recreará la referencia a sí mismo, a partir de Firefox 24. Por ejemplo:</p> + +<pre class="brush: js">var obj1 = {}; +var obj2 = { a: obj1 }; +obj1.b = obj2; + +console.log('Ciclico: ' + (obj1.b.a == obj1)); + +var objSource = obj1.toSource(); // regresa "({b:{a:{}}})" + +obj1 = eval(objSource); + +console.log('Ciclico: ' + (obj1.b.a == obj1)); +</pre> + +<p>Si una estructura cíclica es usada y se necesita el método <code>toSource()</code>, el objeto debe proveer la sobreescritura de <code>toSource()</code>, ya sea usando una referencia a un constructor o proveyendo una función anónima.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Usando_toSource()">Usando <code>toSource()</code></h3> + +<p>El código siguiente define el objeto tipo <code>Dog</code> y crea a <code>theDog</code>, un objeto tipo <code>Dog</code>:</p> + +<pre class="brush: js">function Dog(name, breed, color, sex) { + this.name = name; + this.breed = breed; + this.color = color; + this.sex = sex; +} + +theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female'); +</pre> + +<p>Llamando al método <code>toSource() de</code> <code>theDog</code> muestra el código JavaScript que define al objeto:</p> + +<pre class="brush: js">theDog.toSource(); +// returns ({name:"Gabby", breed:"Lab", color:"chocolate", sex:"female"}) +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>No es parte de ningún estándar. Implementado en JavaScript 1.3.</p> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.toSource")}}</p> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/tostring/index.html b/files/es/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..a9ffc11535 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,70 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/toString +tags: + - JavaScript + - Method + - Object + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +<div>{{JSRef("Objetos_globales", "Object")}}</div> + +<h2 id="Resumen" name="Resumen">Resumen</h2> + +<p>Devuelve una cadena que representa al objeto.</p> + +<h2 id="Sintaxis" name="Sintaxis">Sintaxis</h2> + +<p><code>toString() </code></p> + +<h2 id="Descripci.C3.B3n" name="Descripci.C3.B3n">Descripción</h2> + +<p>Todos los objetos tienen un método <code>toString</code> que se llama automáticamente cuando el objeto se representa como un valor de texto o cuando un objeto se referencia de tal manera que se espera una cadena. Por defecto, el método <code>toString</code> es heredado por todos los objetos que descienden de <code>Object</code>. Si este método no se sobreescribe en el objeto personalizado, <code>toString</code> devuelve <code>{{ mediawiki.external('object<em>type</em> ') }}</code>, donde <code><em>type</em> </code> es el tipo de objeto. El siguiente código ilustra esto:</p> + +<pre class="brush: js">var objeto = new Object(); +objeto.toString(); // Devuelve [object Object] +</pre> + +<h3 id="Examples" name="Examples">Ejemplos</h3> + +<h4 id="Sobreescribir_el_m.C3.A9todo_por_defecto_toString" name="Sobreescribir_el_m.C3.A9todo_por_defecto_toString">Sobreescribir el método por defecto <code>toString</code></h4> + +<p>Puede crear una función que sea llamada en lugar del método predeterminado <code>toString</code>. El método <code>toString</code> no toma argumentos y debería devolver una cadena. El método <code>toString</code> que cree puede ser cualquier valor que quiera, pero será más útil si aporta información sobre el objeto.</p> + +<p>El siguiente código define el tipo de objeto <code>Perro</code> y crea <code>elPerro</code>, un objeto de tipo <code>Perro</code>:</p> + +<pre class="brush: js">function Perro(nombre,criadero,color,sexo) { + this.nombre=nombre; + this.criadero=criadero; + this.color=color; + this.sexo=sexo; +} + +elPerro = new Perro("Gabby","Laboratorio","chocolate","femenino") +</pre> + +<p>Si llama al método <code>toString</code> en el objeto personalizado, devuelve el valor predeterminado heredado de <code>Object</code>:</p> + +<pre class="brush: js">elPerro.toString() //devuelve [object Object] +</pre> + +<p>El siguiente código crea y asigna <code>perroToString</code> para sobreescribir el método predeterminado <code>toString</code>. Esta función genera una cadena que contiene nombre, criadero, color, y sexo del objeto, en la forma "<code>propiedad = valor;</code>".</p> + +<pre class="brush: js">Perro.prototype.toString = function perroToString() { + var retorno = "Perro " + this.nombre + " es " + this.sexo + " " + this.color + " " + this.criadero; + return retorno; +} +</pre> + +<p>Con el código precedente en su lugar, cualquier vez que se use <code>elDog</code> en un contexto de una cadena, JavaScript automáticamente llamará a la función <code>perroToString</code>, la cuál devuelve la siguiente cadena:</p> + +<pre>Perro Gabby es femenino chocolate Laboratorio +</pre> + +<h2 id="Vea_Tambi.C3.A9n" name="Vea_Tambi.C3.A9n">Vea También</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/valueof/index.html b/files/es/web/javascript/reference/global_objects/object/valueof/index.html new file mode 100644 index 0000000000..5cf466078d --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/valueof/index.html @@ -0,0 +1,157 @@ +--- +title: Object.prototype.valueOf() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf +--- +<div>{{JSRef("Global_Objects", "Object")}}</div> + +<p>El método <code><strong>valueOf()</strong></code> retorna el valor primitivo del objeto especificado.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><code><var>object</var>.valueOf()</code></pre> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>El valor primitivo del objeto especificado.</p> + +<p> </p> + +<p>{{EmbedInteractiveExample("pages/js/object-prototype-valueof.html")}}</p> + +<p> </p> + +<h2 id="Description" name="Description">Descripción</h2> + +<p>JavaScript utiliza el método <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> para convertir un objeto a un valor primitivo. Raramente usted necesitará invocar el método </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> por su cuenta; JavaScript lo realizará de forma automática cuando encuentre un objeto, donde un valor primitivo es esperado.</span></p> + +<p>Por defecto, el método <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> es heredado por cada objeto descendiente de </span>{{jsxref("Object")}}.<span style="line-height: 1.5;"> Cada objeto incorporado en el núcleo del lenguaje sobreescribe este método para retornar un valor apropiado. Si un objeto no tiene un valor primitivo, </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> devuelve el objeto en sí.</span></p> + +<p>Puede utilizar <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf </span><span style="line-height: 1.5;">dentro de su propio código para convertir un objeto incorporado en el núcleo del lenguaje en un valor primitivo. Cuando usted crea un objeto personalizado, puede sobreescribir el comportamiento de </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">Object.prototype.valueOf()</span><span style="line-height: 1.5;"> para invocar un método personalizado, en vez de utilizar el método por defecto </span><span style="line-height: 1.5;">{{jsxref("Object")}}.</span></p> + +<h3 id="Sobreescribiendo_valueOf_para_objetos_personalizados">Sobreescribiendo <code>valueOf</code> para objetos personalizados</h3> + +<p>Puede crear una función para ser invocada en lugar de utilizar el método <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> por defecto. Su función no debe contener ningún parámetro.</span></p> + +<p><span style="line-height: 1.5;">Suponga que tiene un objeto de tipo </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">myNumberType</span><span style="line-height: 1.5;"> y usted quiere crear un método </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> para este. El código a continuación asigna una función personalizada al método </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;">:</span></p> + +<pre class="brush: js">myNumberType.prototype.valueOf = function() { return customPrimitiveValue; };</pre> + +<p>Al tener el código anterior funcionando, cada vez que un objeto de tipo <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">myNumberType</span><span style="line-height: 1.5;"> es utilizado en un contexto donde deba ser representado por un valor primitivo, JavaScript automáticamente invocará la función definida en el código anterior.</span></p> + +<p><span style="line-height: 1.5;">El método </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;"> es invocado usualmente por JavaScript pero usted puede invocarlo directamente como sigue a continuación:</span></p> + +<pre class="brush: js">myNumber.valueOf()</pre> + +<div class="note"> +<p><strong>Nota: </strong>Objetos en contextos de string realizan la conversión a string a través del método <span style="line-height: 1.5;">{{jsxref("Object.toString", "toString()")}} </span><span style="line-height: 1.5;">, el cual, es diferente de </span><span style="line-height: 1.5;">{{jsxref("String")}}</span><span style="line-height: 1.5;"> para convertir objetos a primitivos string utilizando el método </span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">valueOf</span><span style="line-height: 1.5;">. Todos los objetos pueden ser convertidos a string, si solo "</span><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">[object </span><em>type</em><span style="font-family: 'Courier New','Andale Mono',monospace; line-height: 1.5;">]</span><span style="line-height: 1.5;">". Pero muchos objetos no se pueden convertir a number, boolean o function.</span></p> +</div> + +<h2 id="Examples" name="Examples">Ejemplos</h2> + +<h3 id="Example:_Using_valueOf" name="Example:_Using_valueOf">Utilizando <code>valueOf</code></h3> + +<pre class="brush: js">function myNumberType(n) { + this.number = n; +} + +myNumberType.prototype.valueOf = function() { + return this.number; +}; + +myObj = new myNumberType(4); +myObj + 3; // 7 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Commentario</th> + </tr> + <tr> + <td>ECMAScript 1ra Edición.</td> + <td>Estándar</td> + <td>Definición inicial. Implementado en JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.4', 'Object.prototype.valueOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> + <p> </p> + </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}</td> + <td>{{Spec2('ESDraft')}} </td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_Navegadores">Compatibilidad con Navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Elemento</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Elemento</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Soporte Básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Vea también</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> + <li>{{jsxref("parseInt", "parseInt()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/object/values/index.html b/files/es/web/javascript/reference/global_objects/object/values/index.html new file mode 100644 index 0000000000..81b56ef1e0 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/object/values/index.html @@ -0,0 +1,97 @@ +--- +title: Object.values() +slug: Web/JavaScript/Referencia/Objetos_globales/Object/values +tags: + - JavaScript + - Objeto + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/values +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Object.values()</strong></code><strong> </strong>devuelve un array con los valores correspondientes a las propiedades <strong>enumerables</strong> de un objeto. Las propiedades son devueltas en el mismo orden a como lo haría un bucle {{jsxref("Statements/for...in", "for...in")}} (la única diferencia es que un bucle <code>for-in</code> también enumera las propiedades en la cadena de prototipo de un objeto).</p> + +<p>{{EmbedInteractiveExample("pages/js/object-values.html")}}</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox">Object.values(<var>obj</var>)</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>Objeto cuyas propiedades enumerables serán devueltas.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un <code>array</code><strong> </strong>con las propiedades enumerables del objeto pasado como parámetro.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>El método <code>Object.values()</code><strong> </strong>devuelve un array cuyos elementos son valores de propiedades enumarables que se encuentran en el objeto. El orden de las propiedades es el mismo que el dado cuando se recorre el objeto de forma manual.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<pre class="brush: js">var obj = { foo: 'bar', baz: 42 }; +console.log(Object.values(obj)); // ['bar', 42] + +// array como objeto +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.values(obj)); // ['a', 'b', 'c'] + +// array como objeto con una ordenación aleatoria de las claves +var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.values(an_obj)); // ['b', 'c', 'a'] + +// getFoo no es una propiedade enumerable, por lo que como se observa, no se devuelve +var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); +my_obj.foo = 'bar'; +console.log(Object.values(my_obj)); // ['bar'] + +// parámetros que no son Objetos<strong> </strong>se fuerzan a que se comporten como tal +console.log(Object.values('foo')); // ['f', 'o', 'o'] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Para dar soporte compatible con <code>Object.values()</code> a entornos antiguos que no la soportan de forma nativa, puedes encontrar un Polyfill<strong> </strong>en <a href="https://github.com/tc39/proposal-object-values-entries">tc39/proposal-object-values-entries</a> o en los repositorios <a href="https://github.com/es-shims/Object.values">es-shims/Object.values</a>.</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definición inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-object.values', 'Object.values')}}</td> + <td>{{Spec2('ES8')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<div>{{Compat("javascript.builtins.Object.values")}}</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li><a href="/es/docs/Web/JavaScript/enumeracion_y_propietario_de_propiedades">Enumeración y propietarios de propiedades</a></li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.entries()")}}</li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> +</ul> |