From a55b575e8089ee6cab7c5c262a7e6db55d0e34d6 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:46:50 +0100 Subject: unslug es: move --- .../object/__definegetter__/index.html | 144 +++++++ .../object/__lookupgetter__/index.html | 84 +++++ .../global_objects/object/assign/index.html | 274 ++++++++++++++ .../global_objects/object/constructor/index.html | 161 ++++++++ .../global_objects/object/create/index.html | 377 ++++++++++++++++++ .../object/defineproperties/index.html | 194 ++++++++++ .../object/defineproperty/index.html | 419 +++++++++++++++++++++ .../global_objects/object/entries/index.html | 161 ++++++++ .../global_objects/object/freeze/index.html | 174 +++++++++ .../global_objects/object/fromentries/index.html | 106 ++++++ .../object/getownpropertydescriptor/index.html | 161 ++++++++ .../object/getownpropertydescriptors/index.html | 117 ++++++ .../object/getownpropertynames/index.html | 163 ++++++++ .../object/getownpropertysymbols/index.html | 123 ++++++ .../object/getprototypeof/index.html | 137 +++++++ .../object/hasownproperty/index.html | 186 +++++++++ .../reference/global_objects/object/index.html | 187 +++++++++ .../reference/global_objects/object/is/index.html | 172 +++++++++ .../global_objects/object/isextensible/index.html | 144 +++++++ .../global_objects/object/isfrozen/index.html | 190 ++++++++++ .../global_objects/object/isprototypeof/index.html | 158 ++++++++ .../global_objects/object/issealed/index.html | 140 +++++++ .../global_objects/object/keys/index.html | 156 ++++++++ .../object/preventextensions/index.html | 176 +++++++++ .../object/propertyisenumerable/index.html | 185 +++++++++ .../global_objects/object/proto/index.html | 128 +++++++ .../global_objects/object/seal/index.html | 167 ++++++++ .../object/setprototypeof/index.html | 237 ++++++++++++ .../object/tolocalestring/index.html | 106 ++++++ .../global_objects/object/tosource/index.html | 126 +++++++ .../global_objects/object/tostring/index.html | 70 ++++ .../global_objects/object/valueof/index.html | 157 ++++++++ .../global_objects/object/values/index.html | 97 +++++ 33 files changed, 5577 insertions(+) create mode 100644 files/es/web/javascript/reference/global_objects/object/__definegetter__/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/entries/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/fromentries/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/getownpropertynames/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/getownpropertysymbols/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/is/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/isextensible/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/isfrozen/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/isprototypeof/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/issealed/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/propertyisenumerable/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/proto/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/seal/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/setprototypeof/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/tolocalestring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/tosource/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/valueof/index.html create mode 100644 files/es/web/javascript/reference/global_objects/object/values/index.html (limited to 'files/es/web/javascript/reference/global_objects/object') 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__ +--- +
{{JSRef}}
+ +
+

Esta característica está obsoleta en favor de definir getters usando el object initializer syntax o la API {{jsxref("Object.defineProperty()")}}.

+ +

En todo caso, como es ampliamente implementada y usada en la Web,  es poco probable que los navegadores dejen de implementarla.

+
+ +

El método __defineGetter__ enlaza una propiedad de un objeto a una función a ser llamada cuando esa propiedad es buscada.

+ +

Sintaxis

+ +
obj.__defineGetter__(prop, func)
+ +

Parámetros

+ +
+
prop
+
Un texto (string) que contiene el nombre de la propiedad para enlazar la función dada.
+
func
+
A function to be bound to a lookup of the specified property.
+
+ +

Descripción

+ +

The __defineGetter__ allows a {{jsxref("Operators/get", "getter", "", 1)}} to be defined on a pre-existing object.

+ +

Ejemplos

+ +
// 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
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('JavaScript', '#object.prototype.__definegetter__', 'Object.prototype.__defineGetter__()')}}{{Spec2('JavaScript')}} 
+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("11")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Mira también

+ + 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__ +--- +
{{JSRef}} {{deprecated_header}}
+ +

Los __lookupGetter__ metodos retornan la funcion  enlazada como un getter para especificar la propiedad.

+ +

Syntax

+ +
obj.__lookupGetter__(sprop)
+ +

Parameters

+ +
+
sprop
+
A string containing the name of the property whose getter should be returned.
+
+ +

Return value

+ +

The function bound as a getter to the specified property.

+ +

Description

+ +

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. __lookupGetter__ can be used to obtain a reference to the getter function.

+ +

It is now possible to do this in a standardized way using {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.getPrototypeOf()")}}.

+ +

Examples

+ +
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'; })
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.prototype.__lookupGetter__', 'Object.prototype.__lookupGetter__()')}}{{Spec2('ESDraft')}}Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.lookupGetter")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.assign() copia todas las propiedades enumerables de uno o más objetos fuente a un objeto destino. Devuelve el objeto destino. 

+ +
{{EmbedInteractiveExample("pages/js/object-assign.html")}}
+ +

Sintaxis

+ +
Object.assign(objetivo, ...fuentes)
+ +

Parámetros

+ +
+
objetivo
+
El objeto destino.
+
fuentes
+
Los objetos origen.
+
+ +

Valor devuelto

+ +

El objeto destino.

+ +

Descripción

+ +

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.

+ +

El método Object.assign() copia sólo las propiedades enumerables y propias del objeto origen a un objeto destino. Usa [[Get]] en la origen y [[Set]] en el destino, por lo que invocará los métodos de acceso y establecimiento (getters y setters). Por consiguiente asignará 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 (getters). Para copiar definiciones de propiedades en prototipos, incluyendo su enumerabilidad, se deben usar {{jsxref("Object.getOwnPropertyDescriptor()")}} y {{jsxref("Object.defineProperty()")}}.

+ +

Tanto las propiedades {{jsxref("String")}} como {{jsxref("Symbol")}} son copiadas.

+ +

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.

+ +

Note que Object.assign() no lanza excepciones al encontrar en las fuentes propiedades {{jsxref("null")}} o {{jsxref("undefined")}}.

+ +

Ejemplos

+ +

Clonando un objeto

+ +
var obj = { a: 1 };
+var copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+
+ +

Advertencia para clonado profundo

+ +

Para un clonado profundo, necesitamos usar otra alternativa ya que Object.assign() 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.

+ +
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();
+ +

Fusionando objetos

+ +
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.
+ +

Fusionando objetos con las mismas propiedades

+ +
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 }
+ +

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.

+ +

Copiando propiedades de tipo símbolo

+ +
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)]
+
+ +

Las propiedades heredadas y las no enumerables no pueden ser copiadas

+ +
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 }
+
+ +

Los tipos primitivos serán encapsulados en objetos

+ +
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" }
+
+ +

Las excepciones interrumpen la tarea de copiado

+ +
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.
+
+ +

Copiando métodos de acceso

+ +
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 } }
+
+ +

Polyfill

+ +

Este {{Glossary("Polyfill","polyfill")}} no soporta propiedades símbolo, ya que ES5 no tiene símbolos.

+ +
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
+  });
+}
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Definición inicial.
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad con navegadores

+ +
+

{{Compat("javascript.builtins.Object.assign")}}

+
+ +

Ver también

+ + 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 +--- +
{{JSRef("Objetos_globales", "Object")}}
+ +

Resumen

+ +

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'.

+ +

Descripción

+ +

Todos los objetos tienen una propiedad constructor. Los objetos creados sin explicitar el uso de una función (como son los objetos y las cadenas literales) tendrán una propiedad de constructor que apunta al tipo de constructor del Objeto Fundamento para ese objeto.

+ +
var o = {};
+o.constructor === Object; // true
+
+var a = [];
+a.constructor === Array; // true
+
+var n = new Number(3);
+n.constructor === Number; // true
+ +

Ejemplos

+ +

Ejemplo: Mostrando el constructor de un objeto.

+ +

El siguiente ejemplo crea un prototipo, Tree, y un objeto de este tipo, theTree. El ejemplo muestra entonces la propiedad constructor para el objeto theTree.

+ +
function Tree (name) {
+   this.name = name;
+}
+
+var theTree = new Tree( "Redwood" );
+console.log( "theTree.constructor is " + theTree.constructor );
+ +

Este ejemplo muestra la siguiente salida:

+ +
theTree.constructor is function Tree (name) {
+    this.name = name;
+}
+ +

Ejemplo: Cambiando el constructor de un objeto.

+ +

El siguiente ejemplo demuestra como modificar el valor del constructor de objetos genéricos. Solo true, 1 y "test" 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.

+ +
function Type () {}
+
+var types = [
+    new Array(),
+    [],
+    new Boolean(),
+    true,             // no cambia
+    new Date(),
+    new Error(),
+    new Function(),
+    function () {},
+    Math,
+    new Number(),
+    1,                // no cambia
+    new Object(),
+    {},
+    new RegExp(),
+    /(?:)/,
+    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" ) );
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificacionesEstatusComentario
ECMAScript 1ra. Edición. Implementado en JavaScript 1.1Estandar.Definición inicial.
{{SpecName('ES5.1', '#sec-15.2.4.1', 'Objectprototype.constructor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

 

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 +--- +
{{JSRef}}
+ +

El método Object.create() crea un objeto nuevo, utilizando un objeto existente como el prototipo del nuevo objeto creado.

+ +
{{EmbedInteractiveExample("pages/js/object-create.html")}}
+ +
+ +
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).
+ +

Sintaxis

+ +
Object.create(proto[, propertiesObject])
+ +

Parámetros

+ +
+
proto
+
Objeto el cual debe ser el prototipo del nuevo objeto creado.
+
propertiesObject
+
Opcional. Si se especifica y no es {{jsxref("undefined")}}, un objeto cuyas propiedades enumerables propias (es decir, aquellas propiedades definidas sobre si mismo y no 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")}}.
+
+ +

Valor devuelto

+ +

Un nuevo objeto con el prototipo y propiedades del objeto especificado.

+ +

Excepciones

+ +

Una excepción {{jsxref("TypeError")}} si el parámetro propertiesObject es {{jsxref("null")}} o un objeto envolvente no primitivo.

+ +

Ejemplos

+ +

Herencia clásica con Object.create()

+ +

Debajo se encuentra un ejemplo de cómo usar Object.create() para lograr herencia clásica. Este es para herencia simple, la cual es todo lo que soporta JavaScript.

+ +
// 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.'
+
+ +

Si desea heredar desde múltiples objetos, entonces los mixins son una posibilidad.

+ +
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
+};
+
+ +

{{jsxref("Object.assign()")}} copia las propiedades del prototipo OtherSuperClass al prototipo de MyClass, haciéndolas disponibles en todas las instancias de MyClass. Object.assign() se introdujo con ES2015 y tiene polyfill. Si el soporte para navegadores antiguos es necesario, se puede utilizar jQuery.extend()_.assign().

+ +

Usando el argumento propertiesObject con Object.create()

+ +
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
+
+// para especificar una propiedad en ES3
+
+o2 = Object.create({}, { p: {
+      value: 42,
+      writable: true,
+      enumerable: true,
+      configurable: true }
+});
+
+ +

Objetos personalizados y nulos

+ +

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:

+ +
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...
+
+ +

Como se muestra arriba, todo parece normal hasta ahora. Sin embargo, al intentar usar estos objetos, sus diferencias se hacen evidentes rápidamente:

+ +
> "oco is: " + oco // Muestra "ocn is: [object Object]"
+
+> "ocn is: " + ocn // Arroja error: Cannot convert object to primitive value
+
+ +

Probar solo algunas de las funciones incorporadas más básicas muestra la magnitud del problema más claramente:

+ +
> 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"
+
+ +

Como se dijo, estas diferencias pueden hacer que la depuración e incluso problemas aparentemente simples se pierdan rápidamente. Por ejemplo:

+ +

Una función simple de depuración:

+ +
// 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" )  }
+}
+ +

Resultados no tan simples: (especialmente si la captura silenciosa de errores había ocultado los mensajes de error)

+ +
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.
+
+ +

(Pero si se crea el mismo objeto simplemente en un orden diferente, al menos en algunas implementaciones ...)

+ +
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.
+ +

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.

+ +

Algunas NO-soluciones

+ +

A good solution for the missing object-methods is not immediately apparent.

+ +

Adding the missing object-method directly from the standard-object does NOT work:

+ +
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
+
+> ocn.toString // shows "toString() { [native code] }" -- missing method seems to be there now
+> 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
+
+ +


+ 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 directly added:

+ +
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  
+
+> ocn.toString() // error: ocn.toString is not a function
+
+ +


+ Adding the missing object-method by using the standard-object as new object's prototype does not work either:

+ +
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
+
+ +

Algunas soluciones aceptables

+ +

Again, adding the missing object-method directly from the standard-object does NOT work. However, adding the generic method directly, DOES:

+ +
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]
+
+ +

However, setting the generic prototype as the new object's prototype works even better:

+ +
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)
+
+ +

(In addition to all the string-related functions shown above, this also adds:)

+ +
> 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.
+
+ +

As shown, objects modified this way now look very much like ordinary objects.

+ +

Polyfill

+ +

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.

+ +

Note that while the setting of null as [[Prototype]] is supported in the real ES5 Object.create, this polyfill cannot support it due to a limitation inherent in versions of ECMAScript lower than 5.

+ +
 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();
+    };
+}
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}{{Spec2('ES5.1')}}Definición inicial. Implementado en JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.create', 'Object.create')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad con navegadores

+ +
{{Compat("javascript.builtins.Object.create")}}
+ +

Ver también

+ + 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 +--- +
{{JSRef("Objetos_globales", "Object")}}
+ +

Sumario

+ +

El metodo Object.defineProperties() define nuevas o modifica propiedades existentes directamente en el objeto, retornando el objeto.

+ +

Sintáxis

+ +
Object.defineProperties(obj, propiedades)
+ +

Parámetros

+ +
+
obj
+
El objeto sobre el cual se crearán o modificaran sus propiedades.
+
propiedades
+
Un objeto cuyas propiedades enumerables propias consituyen descriptores para las propiedades a ser definidas o modificadas.
+
+ +

Descripción

+ +

Object.defineProperties, en escencia, define todas las propiedades correspondientes a las propiedades propias con capacidad de enumeración de props en el objeto objrops.

+ +

Ejemplo

+ +
Object.defineProperties(obj, {
+  "property1": {
+    value: true,
+    writable: true
+  },
+  "property2": {
+    value: "Hello",
+    writable: false
+  }
+  // etc. etc.
+});
+ +

Polyfill

+ +

Asumiendo una ejecución pristina del entorno con todos los nombres y propiedades referidas a sus valores iniciales, Object.defineProperties es casi completamente equivalente (note el comentario en isCallable) a la siguiente reimplementación de JavaScript:

+ +
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;
+}
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}Definición inicial. Implementada en JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}} 
+ +

Compatibilidad de navegadores

+ +

Basado en Kangax's compat tables.

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Soporte básico{{CompatGeckoDesktop("2")}}5 (previous versions untested)911.605
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Soporte básico{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatUnknown}}11.50{{CompatVersionUnknown}}
+
+ +

Ver también

+ + 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 +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Resumen

+ +

El  método estático Object.defineProperty() define una nueva propiedad sobre un objeto, o modifica una ya existente, y devuelve el objeto modificado.

+ +
+

Nota: Ud. puede llamar a este método directamente mediante el constructor {{jsxref("Object")}} en vez de crear una instancia del tipo Object.

+
+ +

Sintaxis

+ +
Object.defineProperty(obj, prop, descriptor)
+ +

Parámetros

+ +
+
obj
+
El objeto sobre el cual se define la propiedad.
+
prop
+
El nombre de la propiedad a ser definida o modificada.
+
descriptor
+
El descriptor de la propiedad que está siendo definida o modificada.
+
+ +

Descripción

+ +

Este método permite añadir o modificar una propiedad en un objeto.

+ +

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")}}.

+ +

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.

+ +

Existen dos tipos de descriptores: De datos y de acceso.  Un descriptor de datos 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.

+ +

Ambos tipos de descriptores son objetos y comparten las siguientes claves opcionales:

+ +
+
configurable
+
true si y solo si el tipo de descriptor de propiedad puede modificarse y si la propiedad puede ser eliminada del correspondiente objeto.
+ Por defecto es false.
+
enumerable
+
true si y solo si dicha propiedad se muestra durante la enumeración de las propiedades del objeto correspondiente.
+ Por defecto es false.
+
+ +

Un descriptor de datos tiene además las siguientes claves opcionales:

+ +
+
value
+
El valor asociado a la propiedad. Puede ser cualquier tipo valido de JavaScript  (number, object, function, etc).
+ Por defecto es {{jsxref("Objetos_Globales/undefined", "undefined")}}.
+
writable
+
true Indica si el valor de la propiedad puede modificarse con el  {{jsxref("Operators/Assignment_Operators", "operador de asignación", "", 1)}}.
+ Defaults to false.
+
+ +

Un descriptor de acceso además tiene las siguientes claves opcionales:

+ +
+
get
+
Una función cuyo valor retornado será el que se use como valor de la propiedad.
+ Defaults to {{jsxref("Objetos_Globales/undefined", "undefined")}}.
+
set
+
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.
+ Defaults to {{jsxref("Objetos_Globales/undefined", "undefined")}}.
+
+ +

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__")}}.

+ +
// 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);
+
+ +

Ejemplos

+ +

Si quiere ver algunos ejemplos de utilización del método Object.defineProperty con una sintaxis tipo binary-flags, vea ejemplos adicionales.

+ +

Ejemplo: Creando una propiedad

+ +

Cuando la propiedad especificada no existe en el objeto, Object.defineProperty() 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 value, get y set se establecerán por defecto a {{jsxref("Objetos_Globales/undefined", "undefined")}}. Una propiedad definida sin indicar  get/set/value/writable es denominada “genérica” y  “tipificada” como un descriptor de datos.

+ +
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
+
+ +

Ejemplo: Modificando una propiedad

+ +

Cuando la propiedad realmente existe, Object.defineProperty() 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 false (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.

+ +

Si una propiedad no tiene capacidad de configuración, su atributo writabble solo puede ser cambiada to false.

+ +

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 writable) a menos que el valor actual y el valor nuevo sean los mismos.

+ +

Atributo writable

+ +

Cuando la propiedad de un atributo writable es establecido to false, la propiedad se dice esta "sin capacidad de escritura". No puede ser reasignada.

+ +
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ó
+
+ +

Como es visto en el ejemplo anterior, intentar escribir en una propiedad "sin capacidad de  escritura" no la cambia pero sí arroja un error.

+ +

Atributo enumerable

+ +

El atributo de la propiedad enumerable se define si la propiedad aparece en un ciclo {{jsxref("Statements/for...in", "for...in")}} y {{jsxref("Object.keys()")}} o no.

+ +
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
+
+ +

Atributo configurable

+ +

El atributo configurable define si la propiedad puede ser eliminada del objeto, y si sus atributos (excepto writable) pueden ser modificados

+ +
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
+
+ +

Si o.a tuviese configurable  a true, no se habrían arrojado errores y la propiedad habría sido eliminada. 

+ +

Ejemplo: Añadiendo propiedades y valores por defecto

+ +

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 Object.defineProperty(), como se muestra en el siguiente ejemplo:

+ +
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
+});
+
+ +

Ejemplo: Setters y Getters a medida

+ +

Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

+ +
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 }]
+
+ +

or

+ +
var pattern = {
+    get: function () {
+        return 'I always return this string, whatever you have assigned';
+    },
+    set: function () {
+        this.myname = 'this is my name string';
+    }
+};
+
+
+function TestDefineSetAndGet() {
+    Object.defineProperty(this, 'myproperty', pattern);
+}
+
+
+var instance = new TestDefineSetAndGet();
+instance.myproperty = 'test';
+console.log(instance.myproperty); // I always return this string, whatever you have assigned
+
+console.log(instance.myname); // this is my name string
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Soporte Básico{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}} (versiones previas sin testear){{CompatIE("9")}} ({{CompatIE("8")}}, pero solo con objetos DOM y con muchos comportamientos no estándares  See below.){{CompatOpera("11.60")}}{{CompatSafari("5.1")}} ({{CompatSafari("5")}}, but not on DOM objects)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatIE("9")}} and above{{CompatOperaMobile("11.50")}}{{CompatVersionUnknown}}
+
+ +

Based on Kangax's compat tables.

+ +

Redefining the length property of an Array object

+ +

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.

+ +

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.

+ +

Versions of Chrome which implement Object.defineProperty() 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.

+ +

Versions of Safari which implement Object.defineProperty() ignore a length 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.

+ +

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 can rely on it, there's really no good reason to do so.

+ +

Particularidades de Internet Explorer 8

+ +

El método Object.defineProperty() de Internet Explorer sólo puede ser usado en objetos del DOM. Algunas explicaciones al respecto:

+ + + +

See also

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.entries() 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).

+ +

Sintaxis

+ +
Object.entries(obj)
+ +

Parámetros

+ +
+
obj
+
The object whose enumerable own property [key, value] pairs are to be returned.
+
+ +

Valor de retorno

+ +

An array of the given object's own enumerable property [key, value] pairs.

+ +

Descripción

+ +

Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.

+ +

Ejemplos

+ +
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"
+});
+
+ +

Converting an Object to a Map

+ +

The {{jsxref("Map", "new Map()")}} constructor accepts an iterable of entries. With Object.entries, you can easily convert from {{jsxref("Object")}} to {{jsxref("Map")}}:

+ +
var obj = { foo: 'bar', baz: 42 };
+var map = new Map(Object.entries(obj));
+console.log(map); // Map { foo: "bar", baz: 42 }
+ +

Polyfill

+ +

To add compatible Object.entries support in older environments that do not natively support it, you can find a Polyfill in the tc39/proposal-object-values-entries or in the es-shims/Object.entries repositories.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.entries', 'Object.entries')}}{{Spec2('ESDraft')}}Initial definition.
{{SpecName('ES8', '#sec-object.entries', 'Object.entries')}}{{Spec2('ES8')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(54)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(47)}}{{CompatNo}}{{CompatNo}}{{CompatSafari(10.1)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(54)}}{{CompatChrome(54)}}{{CompatVersionUnknown}}{{CompatGeckoMobile(47)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.freeze() congela 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.

+ +
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
+ + + +

Sintaxis

+ +
Object.freeze(obj)
+ +

Parámetros

+ +
+
obj
+
El objeto a congelar.
+
+ +

Valor devuelto

+ +

El mismo objeto

+ +

Descripción

+ +

Nada puede ser agregado o removido de las propiedades establecidas de un objeto congelado. Cualquier intento de hacerlo fallará, ya sea de manera silenciosa o arrojando una excepción {{jsxref("TypeError")}} (más comunmente, pero no exclusivamente, en {{jsxref("Strict_mode", "strict mode", "", 1)}}).

+ +

Los valores no pueden ser cambiados por propiedades de datos. Propiedades de acceso (getters y setters) 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 congelados tambien.

+ +

La función retorna el mismo objeto pasado en ella, no crea una copia congelada

+ +

Ejemplos

+ +

Congelando Objetos

+ +
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 congelar
+// 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}
+
+ +

El siguiente ejemplo muestra que los valores de objetos en un objeto congelado pueden ser mutados (la congelación es superficial).

+ +
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
+
+ +

Notas

+ +

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 congelado cualquiera, simplemente lo regresa.

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // Código ES5
+
+> Object.freeze(1)
+1                             // Código ES6
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}{{Spec2('ES5.1')}}Definición inicial. Implementado en JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad de navegadores

+ +

{{Compat("javascript.builtins.Object.freeze")}}

+ +

Mira también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.fromEntries() transforma una lista de pares con [clave-valor] en un objeto.

+ +
{{EmbedInteractiveExample("pages/js/object-fromentries.html")}}
+ + + +

Sintaxis

+ +
Object.fromEntries(iterable);
+ +

Parámetros

+ +
+
iterador
+
Un iterador como {{jsxref("Array")}}, {{jsxref("Map")}} u otros objetos que implementen el protocolo iterable.
+
+ +

Valor de retorno

+ +

Un nuevo objeto cuyas propiedades son dadas por las entradas del iterador.

+ +

Descripción

+ +

El método Object.fromEntries() toma una lista de pares con clave-valor y devuelve un nuevo objeto cuyas propiedades son dadas por éstas entradas. El argumento iterador se espera que sea un objeto que implemente un método @@iterator, 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.

+ +

Object.fromEntries() realiza lo inverso de {{jsxref("Object.entries()")}}.

+ +

Ejemplos

+ +

Convirtiendo un Map en un Objeto

+ +

Con Object.fromEntries, puedes convertir de un {{jsxref("Map")}} a un {{jsxref("Object")}}:

+ +
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
+const obj = Object.fromEntries(map);
+console.log(obj); // { foo: "bar", baz: 42 }
+
+ +

Convirtiendo un Arreglo en un Objeto

+ +

Con Object.fromEntries, puedes convertir de un {{jsxref("Array")}} a un {{jsxref("Object")}}:

+ +
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
+const obj = Object.fromEntries(arr);
+console.log(obj); // { 0: "a", 1: "b", 2: "c" }
+
+ +

Transformación de Objetos

+ +

Con Object.fromEntries, su método inverso {{jsxref("Object.entries()")}}, y array métodos de manipulaciín de arreglos, puedes transformar objetos así:

+ +
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 }
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstado
{{SpecName('ESDraft', '#sec-object.fromentries', 'Object.fromEntries')}}Etapa 4
+ +

Compatibilidad de navegadores

+ + + +

{{Compat("javascript.builtins.Object.fromEntries")}}

+ +

Véase tambien

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.getOwnPropertyDescriptor() 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.

+ +

Síntaxis

+ +
Object.getOwnPropertyDescriptor(obj, prop)
+ +

Parametros

+ +
+
obj
+
El objeto en el que se busca la propiedad.
+
prop
+
El nombre de la propiedad del cuál se obtendrá la descripción.
+
+ +

Valor de retorno

+ +

Un descriptor de propiedad de una propiedad dada si existe en el objeto,  {{jsxref("undefined")}} en cualquier otro caso.

+ +

Descripción

+ +

É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()")}}.

+ +

Una descripción de propiedad es un registro con alguno de los siguientes atributos:

+ +
+
value
+
El valor asociado con la propiedad (descriptores de datos unicamente).
+
writable
+
true si y solo si el valor asociado con la propiedad puede ser cambiada (descriptores de datos unicamente).
+
get
+
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).
+
set
+
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).
+
configurable
+
true 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.
+
enumerable
+
true si y solo si ésta propiedad aparece durante la enumeración de las propiedades del objeto correspondiente.
+
+ +

Ejemplos

+ +
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 }
+
+ +

Notas

+ +

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.

+ +
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
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.3', 'Object.getOwnPropertyDescriptor')}}{{Spec2('ES5.1')}}Definición inicial. Implementado en JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.getownpropertydescriptor', 'Object.getOwnPropertyDescriptor')}}{{Spec2('ES6')}}
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("5")}}{{CompatGeckoDesktop("2")}}{{CompatIE("8")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El métodoObject.getOwnPropertyDescriptors() regresa todos los descriptores de propiedad propios de un objeto dado.

+ +
{{EmbedInteractiveExample("pages/js/object-getownpropertydescriptors.html")}}
+ +

Sintáxis

+ +
Object.getOwnPropertyDescriptors(obj)
+ +

Parámetros

+ +
+
obj
+
El objeto para el cual obtener todos los descriptores de propiedad.
+
+ +

Valores devueltos

+ +

Un objeto que contiene todos los descriptores de propiedad propios de un objeto.

+ +

Descripción

+ +

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()")}}.

+ +

Un descriptor de propiedad es un registro con algunos de los siguientes atributos:

+ +
+
value
+
El valor asociado con la propiedad (solo descriptores de datos).
+
writable
+
true si y solo si el valor asociado con la propiedad puede ser cambiado (solo descriptores de datos).
+
get
+
Un función que sirve como un getter para la propiedad, o {{jsxref("undefined")}} si no hay getter (solo descriptores de acceso).
+
set
+
Una función que sirve como un setter para la propiedad, o {{jsxref("undefined")}} si no hay setter (solo descriptores de acceso).
+
configurable
+
true 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.
+
enumerable
+
true si y solo si esta propiedad aparece durante la enumeración de las propiedad en el objeto correspondiente.
+
+ +

Ejemplos

+ +

Creando un clon superficial

+ +

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:

+ +
Object.create(
+  Object.getPrototypeOf(obj),
+  Object.getOwnPropertyDescriptors(obj)
+);
+
+ +

Creando una subclase

+ +

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:

+ +
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í
+  }
+);
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.getownpropertydescriptors', 'Object.getOwnPropertyDescriptors')}}{{Spec2('ESDraft')}}Definición inicial en ECMAScript 2017.
{{SpecName('ES2017', '#sec-object.getownpropertydescriptors', 'Object.getOwnPropertyDescriptors')}}{{Spec2('ES2017')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.getOwnPropertyDescriptors")}}

+
+ +

Ver también:

+ + 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 +--- +
+ {{JSRef("Global_Objects", "Object")}}
+

Resumen

+

El método Object.getOwnPropertyNames() devuelve un array con todas las propiedades (numerables o no) encontradas en un objeto dado.

+

Sintaxis

+
Object.getOwnPropertyNames(obj)
+

Parámetros

+
+
+ obj
+
+ El objeto cuyas propiedades directas, numerables y no-numerables, serán devueltas.
+
+

Descripción

+

Object.getOwnPropertyNames devuelve un array cuyos elementos son strings correspondientes a cada una de las propiedades encontradas directamente en obj. El orden de las propiedades numerables en el array coincide con el expuesto para for...in loop (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.

+

Ejemplos

+
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"
+
+

Si se quiere solo las propiedades numerables, ver {{jsxref("Object.keys")}} o usar un for...in loop (aunque esto devolvería propiedades numerables no directas del objeto pertenecientes a la cadena de prototype a la que pertenezca, a menos que finalmente se filtre con hasOwnProperty()).

+

Items de la cadena prototype no se listan:

+
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"]
+  )
+)
+
+

Get Non-Enumerable Only

+

Aquí se usa la función Array.prototype.filter para quitar las keys numerables (obtenidas con Object.keys) de una lista con todas las keys (obtenida con Object.getOwnPropertynames) dejando solo las no-numerables.

+
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);
+
+

Especificaciones

+ + + + + + + + + + + + + + + + + + +
EspecificaciónStatusComentario
{{SpecName('ES5.1', '#sec-15.2.3.4', 'Object.getOwnPropertyNames')}}{{Spec2('ES5.1')}}Initial definition.
+ Implemented in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.getownpropertynames', 'Object.getOwnPropertyNames')}}{{Spec2('ES6')}} 
+

 Compatibilidad con Navegadores

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support4 (2.0)59125
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+

Based on Kangax's compat table.

+

SpiderMonkey-specific notes

+ +

Ver también

+ 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 +--- +
{{JSRef}}
+ +

El método Object.getOwnPropertySymbols() regresa una colección de todos las propiedades de los simbolos encontrados directamente en un objeto dado.

+ +

Síntaxis

+ +
Object.getOwnPropertySymbols(obj)
+ +

Parametros

+ +
+
obj
+
El objeto del cual los simbolos de propiedades son devueltos.
+
+ +

Descripción

+ +

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.

+ +

Cómo todos los objetos no tienen inicialmente propiedades simbolos propios, Object.getOwnPropertySymbols() regresa una colección vacia a menos que tengas propiedades de simbolos establecidas en tu objeto.

+ +

Ejemplos

+ +
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)
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-object.getownpropertysymbols', 'Object.getOwnPropertySymbols')}}{{Spec2('ES6')}}Definición inicial.
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome(38)}}{{CompatGeckoDesktop("36.0")}}{{CompatNo}}259
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico5.1{{CompatChrome(38)}}{{CompatGeckoMobile("36.0")}}{{CompatNo}}259
+
+ +

Ver también

+ + 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 +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Resumen

+ +

El método Object.getPrototypeOf() devuelve el prototipo (es decir, el valor de la propiedad interna [[Prototype]]) del objeto especificado.

+ +

Sintaxis

+ +
Object.getPrototypeOf(obj)
+ +

Parámetros

+ +
+
obj
+
El objeto cuyo prototipo va a ser devuelto.
+
+ +

Valor Devuelto

+ +

El prototipo del objeto dado. Si no existen propiedades heredadas se devolverá {{jsxref("null")}}.

+ +

Ejemplos

+ +
var proto = {};
+var obj= Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

Notas

+ +

En ES5, lanzará una excepción {{jsxref("Global_Objects/TypeError", "TypeError")}} si el parámetro obj no es un objeto. en ES6, El parámetro será forzado a un {{jsxref("Global_Objects/Object", "Object")}}.

+ +
> Object.getPrototypeOf('foo')
+TypeError: "foo" is not an object  // ES5 code
+> Object.getPrototypeOf('foo')
+String.prototype                   // ES6 code
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Definición inicial.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}} (tal vez en las últimas versiones){{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Based on Kangax's compat table.

+ +

Notas espécificas sobre Opera

+ +

A pesar de que las versiones anteriores de opera no soportan aun Object.getPrototypeOf(), Opera soporta la propiedad no estándar {{jsxref("Object.proto", "__proto__")}} desde Opera 10.50.

+ +

Mira también

+ + 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 +--- +
{{JSRef("Objetos_globales", "Object")}}
+ +

Resumen

+ +

El método hasOwnProperty() devuelve un booleano indicando si el objeto tiene la propiedad especificada.

+ +

Sintaxis

+ +
obj.hasOwnProperty(prop)
+ +

Parámetros

+ +
+
prop
+
El nombre de la propiedad a buscar.
+
+ +

Descripción

+ +

Todo objeto descendiente de Object hereda el método hasOwnProperty. 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.

+ +

Ejemplos

+ +

Ejemplo: usar hasOwnProperty para comprobar la existencia de una propiedad

+ +

El siguiente ejemplo determina si el objeto o contiene una propiedad llamada prop:

+ +
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
+ +

Ejemplo: Directo versus propiedades heredadas

+ +

El siguiente ejemplo diferencia entre propiedades directas y propiedades heredadas a través de la cadena prototype:

+ +
o = new Object();
+o.prop = 'exists';
+o.hasOwnProperty('prop');             // returns true
+o.hasOwnProperty('toString');         // returns false
+o.hasOwnProperty('hasOwnProperty');   // returns false
+ +

Ejemplo: Iterando sobre las propiedades de un objeto

+ +

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()")}}).

+ +
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
+    }
+}
+ +

Ejemplo: hasOwnProperty como una propiedad

+ +

JavaScript no protege el nombre de la propiedad hasOwnProperty; en consecuencia, si existe la posibilidad  de que un objeto pudiera tener la propiedad con ese nombre, es necesario usar un externo hasOwnProperty para obtener los correctos resultados:

+ +
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
+
+ +

Observe que en el último caso no han habido nuevos objetos creados.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificacionesEstadoComentario
ECMAScript 3rd Edition. Implemented in JavaScript 1.5StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
+ +

Compatibilidad de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Véase también

+ + 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 +--- +
{{JSRef}}
+ +
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. 
+ +

El constructor Object crea una envoltura al objeto.

+ +

Sintaxis

+ + + +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

Parámetros

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Los pares de nombres (strings) y los valores (cualquier valor) donde los nombres son separados por una coma.
+
valor
+
Cualquier valor.
+
+ +

Description

+ +

El constructor Object 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.

+ +

Cuando es llamano en un contexto non-constructor, Object se comportará indenticamente a new Object().

+ +

Ver object initializer / literal syntax.

+ +

Propiedades del constructor Object

+ +
+
Object.length
+
Tiene un valor de 1.
+
{{jsxref("Object.prototype")}}
+
Permite añadir propiedades a todos los objetos del tipo Object.
+
+ +

Métodos del constructor  Object

+ +
+
{{jsxref("Object.assign()")}}
+
Copia los valores de todas sus propiedades enumerables desde uno o más objetos fuente a un objeto destino.
+
{{jsxref("Object.create()")}}
+
Crea un nuevo objeto con el prototipo objeto y propiedades específicadas.
+
{{jsxref("Object.defineProperty()")}}
+
Añade la propiedad nombrada descrita por un descriptor dado a un objeto.
+
{{jsxref("Object.defineProperties()")}}
+
Agrega las propiedades nombradas descritas por los descriptores dados a un objeto.
+
{{jsxref("Object.entries()")}}
+
Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.fromEntries()")}}
+
Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyDescriptors()")}}
+
Returns an object containing all own property descriptors for an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable string properties.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property).
+
{{jsxref("Object.values()")}}
+
Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
+
+ +

Object instances and Object prototype object

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
+ +

Deleting a property from an object

+ +

There isn't any method in an Object itself to delete its own properties (e.g. like Map.prototype.delete()). To do so one has to use the delete operator.

+ +

Examples

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

The following examples store {{jsxref("Boolean")}} objects in o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.is() determina si dos valores son iguales.

+ +

Síntaxis

+ +
Object.is(valor1, valor2);
+ +

Parámetros

+ +
+
valor1
+
Primer valor a comparar.
+
valor2
+
Segundo valor a comparar.
+
+ +

Valor return del método

+ +

Este método devuelve un valor de tipo {{jsxref("Boolean")}} indicando si los valores pasados como parámetros son iguales o no.

+ +

Descripción

+ +

Object.is() determina si dos valores son iguales. Dos valores son iguales si se puede asegurar que:

+ + + +

Esta comparación no 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  "" == false siendo true), pero Object.is no obliga a niguno de los valores.

+ +

Esta tampoco 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 -0 y +0 como iguales, y además, trata {{jsxref("Number.NaN")}} como no igual a {{jsxref("NaN")}}.

+ +

Ejemplos

+ +
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
+
+ +

Polyfill para navegadores no ES6

+ +

Object.is() 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 Object.is() en los navegadores que no lo llevan incluído.

+ +
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;
+    }
+  };
+}
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-object.is', 'Object.is')}}{{Spec2('ES6')}}Definición inicial.
+ +

Compatibilidad en navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("30")}}{{CompatGeckoDesktop("22")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("22")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.isExtensible() determina si un objeto es extendible (si puede tener propiedades nuevas agregadas a éste).

+ +

Síntaxis

+ +
Object.isExtensible(obj)
+ +

Parametros

+ +
+
obj
+
El objeto a ser revisado.
+
+ +

Descripción

+ +

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()")}}.

+ +

Ejemplos

+ +
// 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
+
+ +

Notas

+ +

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 false.

+ +
Object.isExtensible(1);
+// TypeError: 1 is not an object (ES5 code)
+
+Object.isExtensible(1);
+// false                         (ES6 code)
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.13', 'Object.isExtensible')}}{{Spec2('ES5.1')}}Definición inicial. Implementada en JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.isextensible', 'Object.isExtensible')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporote básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.isFrozen() determina si un objeto está congelado.

+ +

Síntaxis

+ +
Object.isFrozen(obj)
+ +

Parametros

+ +
+
obj
+
El objeto a ser revisado.
+
+ +

Descripción

+ +

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.

+ +

Ejemplos

+ +
// 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
+
+ +

Notas

+ +

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 true.

+ +
Object.isFrozen(1);
+// TypeError: 1 is not an object (ES5 code)
+
+Object.isFrozen(1);
+// true                          (ES6 code)
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}{{Spec2('ES5.1')}} +

Definición inicial. Implementada en JavaScript 1.8.5.

+
{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicasAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El método isPrototypeOf() comprueba si un objeto se encuentra en la cadena de prototipado de otro.

+ +
+

Nota: isPrototypeOf difiere del operador {{jsxref("Operators/instanceof", "instanceof")}}. En la expresión "object instanceof AFunction", la cadena de prototipado de object es comprobada contra AFunction.prototype, no contra la propia AFunction.

+
+ +

Sintaxis

+ +
prototypeObj.isPrototypeOf(obj)
+ +

Parámetros

+ +
+
prototypeObj
+
Un objeto para ver comprobado contra cada vínculo en la cadena de prototipado del argumento object.
+
object
+
El object sobre cuya cadena de prototipado se realizará la búsqueda.
+
+ +

Descripción

+ +

El método isPrototypeOf permite comprobar si un objetyo existe o no en la cadena de prototipado de otro.

+ +

Por ejemplo, considerese la siguiente cadena de prototipado:

+ +
function Fee() {
+  // ...
+}
+
+function Fi() {
+  // ...
+}
+Fi.prototype = new Fee();
+
+function Fo() {
+  // ...
+}
+Fo.prototype = new Fi();
+
+function Fum() {
+  // ...
+}
+Fum.prototype = new Fo();
+
+ +

Al final de la secuencia, si se instanci Fum y se necesita verificar si el prototipo de Fi existe en la cadena de prototipado de Fum prototype chain, puede hacerse esto:

+ +
var fum = new Fum();
+// ...
+
+if (Fi.prototype.isPrototypeOf(fum)) {
+  // do something safe
+}
+
+ +

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.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoObservaciones
{{SpecName('ES3')}}{{Spec2('ES3')}}Definición inicial.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
PrestaciónChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
PrestaciónAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.isSealed() si el objeto está sellado.

+ +
{{EmbedInteractiveExample("pages/js/object-issealed.html")}}
+ + + +

Syntax

+ +
Object.isSealed(obj)
+ +

Parámetros

+ +
+
obj
+
El objeto que debe ser verificado.
+
+ +

Valor devuelto

+ +

Un {{jsxref("Boolean")}} indicando si el objeto dado está sellado.

+ +

Descripción

+ +

Devuelve true si el objeto está sellado, de lo contrario devuelve false. 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).

+ +

Ejemplos

+ +
// 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)
+
+ +

Notes

+ +

En ES5, si el argumento de este método no es un objeto (primitivo), entonces causará un {{jsxref("TypeError")}}. En ES2015, un argumento que no sea un objeto será tratado como si fuera un objeto sellado ordinario, simplemente devuelve true.

+ +
Object.isSealed(1);
+// TypeError: 1 no es un objeto (ES5 code)
+
+Object.isSealed(1);
+// true                          (ES2015 code)
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}{{Spec2('ES5.1')}}Definición inicial. Implementada en JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.isSealed")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Resumen

+ +

El método Object.keys() devuelve un array de las propiedades names de un objeto, en el mismo orden como se obtienen en un loop normal

+ +

Sintaxis

+ +
Object.keys(obj)
+ +

Parámetros

+ +
+
obj
+
El objeto cuyas propiedades enumerables serán devueltas.
+
+ +

Valor de retorno

+ +

Un array de strings que representan toda las propiedades  del objeto

+ +

Descripción

+ +

Object.keys 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.

+ +

Ejemplos

+ +
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']
+
+ +

Si quieres todas las propiedades, incluso las no enumerables, mira {{jsxref("Object.getOwnPropertyNames()")}}.

+ +

Notas

+ +

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.

+ +
> Object.keys("foo")
+// TypeError: "foo" is not an object  (ES5)
+
+> Object.keys("foo")
+// ["0", "1", "2"]                    (ES2015)
+ +

Polyfill

+ +

Para añadir soporte Object.keys en entornos más antiguos que no lo soportan de forma nativa, copia el siguiente fragmento:

+ +
// 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;
+    };
+  }());
+}
+
+ +

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.

+ +

Para un simple Polyfill del Navegador, mira Javascript - Compatibilidad de Object.keys en Navegadores.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Definición inicial. Implementado en JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad con navegadores

+ +
{{Compat("javascript.builtins.Object.keys")}}
+ + + +

Mira también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.preventExtensions() previene que nuevas propiedades sean agregadas a un objeto (p.e. previene la extensión futuras al objeto).

+ +

Sintaxis

+ +
Object.preventExtensions(obj)
+ +

Parametros

+ +
+
obj
+
El objeto que debería hacerse inextendible.
+
+ +

Descripción

+ +

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)}}).

+ +

Object.preventExtensions() solo previene la adición de propiedades propias. Las propiedades aún pueden ser agregadas a object.prototype. Sin embargo, llamar Object.preventExtensions() sobre un objeto tambien prevendrá extensiones sobre la propiedad {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}}.

+ +

Si hay una manera de cambiar un objeto extendible a uno no-extendible, hay una manera de hacer lo opuesto en ECMAScript 5.

+ +

Ejemplos

+ +
// 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
+
+ +

Notas

+ +

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.

+ +
Object.preventExtensions(1);
+// TypeError: 1 is not an object (ES5 code)
+
+Object.preventExtensions(1);
+// 1                             (ES6 code)
+
+ +

Especificación

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Definición inicial. Implementada en JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
Comportamiento en ES6 para un no-objeto pasado como argumento{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Comportamiento en ES6 para no-objetos pasados como argumentos{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Mira también

+ + 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 +--- +
{{JSRef}}
+ +

El método propertyIsEnumerable() regresa un Boleano indicando si la propiedad especificada es enumerable.

+ +

Sintaxis

+ +
obj.propertyIsEnumerable(prop)
+ +

Parametros

+ +
+
prop
+
Nombre de la propiedad a probar.
+
+ +

Descripción

+ +

Todos los objetos tienen un método propertyIsEnumerable. 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 false.

+ +

Ejemplo

+ +

Uso básico de propertyIsEnumerable

+ +

El siguiente ejemplo muestra el uso de propertyIsEnumerable en objetos y arrays:

+ +
var o = {};
+var a = [];
+o.prop = 'es enumerable';
+a[0] = 'es enumerable';
+
+o.propertyIsEnumerable('prop');   // regresa true
+a.propertyIsEnumerable(0);        // regresa true
+
+ +

Definidas por usuario vs predefinidas

+ +

El siguiente ejemplo demuestra la enumerabilidad de las propiedades definidas por el usuario contra las predefinidas:

+ +
var a = ['es enumerable'];
+
+a.propertyIsEnumerable(0);          // regresa true
+a.propertyIsEnumerable('length');   // regresa false
+
+Math.propertyIsEnumerable('random');   // regresa false
+this.propertyIsEnumerable('Math');     // regresa false
+
+ +

Directa vs  heredadas

+ +
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
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('ES3')}}{{Spec2('ES3')}}Definición inicial.
{{SpecName('ES5.1', '#sec-15.2.4.7', 'Object.prototype.propertyIsEnumerable')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.propertyisenumerable', 'Object.prototype.propertyIsEnumerable')}}{{Spec2('ES6')}} 
+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Notas específicas para Gecko

+ +

Al inicio de JavaScript 1.8.1 (in Firefox 3.6), propertyIsEnumerable('prototype') regresa false en lugar de true; esto hace que el resultado cumpla con la especificación de ECMAScript 5.

+ +

Véase también

+ + 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 +--- +
+

Advertencia: Cambiar la propiedad [[Prototype]] de un objeto es, por como los navegadores modernos optimizan las propiedades de acceso, una operación muy lenta en todos 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 obj.__proto__ = ... sentencia,  sin embargo afecta a  cualquier código que tiene acceso a  cualquier objeto cuya propiedad [[Prototype]] ha sido alterada, por lo que se debe de tener mucho cuidado.

+ +

Si el rendimiento en tu aplicación es necesario, deberías evitar modificar la propiedad [[Prototype]] de un objeto. En su lugar, crea un objecto nuevo con la propiedad [[Prototype]] deseada usando {{jsxref("Object.create()")}}.

+
+ +
+

Advertencia: Mientras Object.prototype.__proto__ 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.

+
+ +
{{JSRef}}
+ +

La propiedad __proto__ 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 [[Prototype]] (ya sea un objeto o {{jsxref("Global_Objects/null", "null")}}) del objeto a través del cual se accede a ella.

+ +

El uso de la propiedad __proto__ 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, la propiedad __proto__ 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 [[Prototype]] de un objeto es una operación muy lenta, por lo que si nos preocupa el rendimiento, debemos de evitarlo).

+ +

La propiedad __proto__ puede ser usada también en un objeto definido de forma literal, para establecer el [[Prototype]] en la creación de este, como alternativa a {{jsxref("Object.create()")}}. Ver: object initializer / literal syntax.

+ +

Síntaxis

+ +
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
+
+ +

Nota: esto es, dos guiones bajos, seguidos de cinco carácteres "proto", seguido de dos guiones bajos mas.

+ +

Descripción

+ +

La función getter __proto__el valor interno del [[Prototype]] 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 fun 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 fun.prototype.  (Esto es, si el constructor no devuelve un objeto de forma explícita, o el fun.prototype ha sido reasignado desde que la instancia fué creada).

+ +

El __proto__ setter la mutación del objeto [[Prototype]] 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.

+ +

Para entender como los prototipos son usados para herencia, ver el artículo Inheritance and the prototype chain.

+ +

La propiedad __proto__ es una simple propiedad de acceso a {{jsxref("Object.prototype")}} que consiste en una función getter y setter. Un acceso a la propiedad  __proto__ 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 __proto__ es encontrada antes {{jsxref("Object.prototype")}} es consultada, esta propiedad sera ocultada por la encontrada en {{jsxref("Object.prototype")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificacionesEstadoComentario
{{SpecName('ES6', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}{{Spec2('ES6')}}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).
+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("11")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Notas de compatibilidad

+ +

Mientras la especificación ECMAScript 2015 (ES6) dicta que el soporte para __proto__ es requerido solo para navegadores web (a pesar de ser normativo), otros medios pueden soportarlo por uso de legado.

+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.seal() 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.

+ +

Sintaxis

+ +
Object.seal(obj)
+ +

Parámetros

+ +
+
obj
+
El objeto que ha de ser sellado.
+
+ +

Descripción

+ +

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)}}).

+ +

La cadena de prototiado permanece inalterada. No obstante, la propiedad {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} es también sellada.

+ +

Retorna una referencia al Objeto pasado.

+ +

Ejemplos

+ +
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
+
+ +

Notas

+ +

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.

+ +
Object.seal(1);
+// TypeError: 1 no es un objeto (código ES5)
+
+Object.seal(1);
+// 1                             (código ES6)
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoObservaciones
{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}{{Spec2('ES5.1')}}Definición inicial. Implementado en  JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
PrestaciónChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
PrestiaciónAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver también

+ + 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 +--- +

{{JSRef}}

+ +

El método Object.setPrototypeOf() establece el prototipo (p.e., la propiedad interna [[Prototype]]) de un objeto especificado a otro objeto o sino establece {{jsxref("null")}}.

+ +
+

Adverdencia: Cambiar la propiedad [[Prototype]] 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 todo 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 obj.__proto___ = ...,  but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using {{jsxref("Object.create()")}}.

+
+ +

Sintaxis

+ +
Object.setPrototypeOf(obj, prototype);
+ +

Parámetros

+ +
+
obj
+
El objeto al que se ha de establecer el prototipo.
+
prototype
+
El nuevo prototipo del objeto, (un objeto o {{jsxref("null")}}).
+
+ +

Descripción

+ +

Arroja una excepción del tipo {{jsxref("TypeError")}} si el objeto cuyo [[Prototype]] se va a modificar no es extensible de acuerdo con {{jsxref("Object.isExtensible()")}}. No hace nada si el parametro prototype 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 [[Prototype]] del obj al valor nuevo.

+ +

Object.setPrototypeOf() 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__")}}.

+ +

Ejemplos

+ +
var dict = Object.setPrototypeOf({}, null);
+
+ +

Polyfill

+ +

Utilizando la vieja propiedad {{jsxref("Object.prototype.__proto__")}}, podemos definir facilmente Object.setPrototypeOf si aún no está disponible:

+ +
// 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;
+}
+
+ +

Agregando cadenas de prototipo

+ +

Una combinación de Object.getPrototypeOf() y {{jsxref("Object.proto", "Object.prototype.__proto__")}} permite agregar una nueva cadena de prototipos al nuevo  prototipo del objeto.

+ +
/**
+*** 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;
+}
+
+ +

Uso

+ +

Primer ejemplo: Agregar una cadena a un prototipo

+ +
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'
+
+ +

Segundo ejemplo: Transofrmando un valor Primitivo en una instancia de su constructor y agregar su cadena al prototipo

+ +
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'
+
+ +

Tercer ejemplo: Agregando una cadena a la Function.prototype de un objeto y agregando una nueva función a la cadena

+ +
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!!'
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-object.setprototypeof', 'Object.setProtoypeOf')}}{{Spec2('ES6')}}Initial definition.
+ +

Compatibilidad del navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("34")}}{{CompatGeckoDesktop("31")}}{{CompatIE("11")}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("31")}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

Ver también

+ + 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 +--- +
{{JSRef}}
+ +

El método toLocaleString() 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.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-tolocalestring.html")}}
+ + + +

Sintaxis

+ +
objeto.toLocaleString()
+ +

Valor de retorno

+ +

Un string que representa al objeto.

+ +

Descripción

+ +

{{jsxref("Object")}}'s toLocaleString devuelve el resultado de llamar a {{jsxref("Object.toString", "toString()")}}.

+ +

Se proporciona esta función para que los objetos dispongan de un método toLocaleString genérico, aunque puede que no todos la utilicen. Véase la lista siguiente.

+ +

Objetos que redefinen toLocaleString

+ + + +

Ejemplos

+ +

Redefinición de toLocaleString() en Array

+ +

En los objetos Array se puede utilizar toLocaleString() para imprimir los valores del array como un string, con indicadores opcionales de configuración regional (como símbolos de moneda) aplicados.

+ +

Por ejemplo:

+ +
const unArray = [4, 7, 10];
+
+let preciosEnEuros = unArray.toLocaleString('fr', { style: 'currency', currency: 'EUR'});
+// "4,00 €,7,00 €,10,00 €"
+ +

Redefinición de toLocaleString() para Date

+ +

En los objetos Date se usa toLocaleString() para imprimir fechas en un formato adecuado a la configuración regional.

+ +

Por ejemplo:

+ +
const unaFecha = new Date(Date.now());
+// "2020-07-07T19:51:44.046Z"
+
+let fechaAleman = unaFecha.toLocaleString('de');
+// "7.7.2020, 21:55:22"
+
+var fechaFrances= unaFecha.toLocaleString('fr');
+//"07/07/2020 à 21:55:22"
+ +

Redefinición de toLocaleString() para Number

+ +

En los objetos Number se usa toLocaleString() para imprimir números de forma adecuada a la configuración regional, p. ej. para usar los separadores de miles correctos.

+ +

Por ejemplo:

+ +
const unNumero = 2901234564;
+// "2901234564"
+
+let numeroAleman = unNumero.toLocaleString('de');
+// "2.901.234.564"
+
+let numeroFrances = unNumero.toLocaleString('fr');
+// "2 901 234 564"
+ +

Especificaciones

+ + + + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-object.prototype.tolocalestring', 'Object.prototype.toLocaleString')}}
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("javascript.builtins.Object.toLocaleString")}}

+ +

Ver también

+ + 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 +--- +
{{JSRef}} {{non-standard_header}}
+ +

El método toSource() regresa una cadena representando el código fuente del objeto.

+ +

Syntax

+ +
Object.toSource();
+obj.toSource();
+
+ +

Return value

+ +

Una cadena representando el código fuente del objeto.

+ +

Description

+ +

EL método toSource() regresa los siguientes valores:

+ + + +

Puedes llamar el método toSource() durante el depurado para examinar el contenido de un objeto.

+ +

Sobreescribir el método toSource()

+ +

Es seguro para los objetos sobreescribir el método toSource(). Por ejemplo:

+ +
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")
+
+ +

Métodos de toSource() incorporados

+ +

Cada tipo fundamental de JavaScript tiene su propio método toSource().  Éstos objetos son:

+ + + +

Limitaciones en objetos cíclicos

+ +

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, toSource() no recreará la referencia a sí mismo, a partir de Firefox 24. Por ejemplo:

+ +
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));
+
+ +

Si una estructura cíclica es usada y se necesita el método toSource(), el objeto debe proveer la sobreescritura de toSource(), ya sea usando una referencia a un constructor o proveyendo una función anónima.

+ +

Ejemplos

+ +

Usando toSource()

+ +

El código siguiente define el objeto tipo Dog y crea a theDog, un objeto tipo Dog:

+ +
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');
+
+ +

Llamando al método toSource() de theDog muestra el código JavaScript que define al objeto:

+ +
theDog.toSource();
+// returns ({name:"Gabby", breed:"Lab", color:"chocolate", sex:"female"})
+
+ +

Especificaciones

+ +

No es parte de ningún estándar. Implementado en JavaScript 1.3.

+ +

Compatibilidad en navegadores

+ +
+ + +

{{Compat("javascript.builtins.Object.toSource")}}

+
+ +

Ver también

+ + 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 +--- +
{{JSRef("Objetos_globales", "Object")}}
+ +

Resumen

+ +

Devuelve una cadena que representa al objeto.

+ +

Sintaxis

+ +

toString()

+ +

Descripción

+ +

Todos los objetos tienen un método toString 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 toString es heredado por todos los objetos que descienden de Object. Si este método no se sobreescribe en el objeto personalizado, toString devuelve {{ mediawiki.external('objecttype ') }}, donde type es el tipo de objeto. El siguiente código ilustra esto:

+ +
var objeto = new Object();
+objeto.toString(); // Devuelve [object Object]
+
+ +

Ejemplos

+ +

Sobreescribir el método por defecto toString

+ +

Puede crear una función que sea llamada en lugar del método predeterminado toString. El método toString no toma argumentos y debería devolver una cadena. El método toString que cree puede ser cualquier valor que quiera, pero será más útil si aporta información sobre el objeto.

+ +

El siguiente código define el tipo de objeto Perro y crea elPerro, un objeto de tipo Perro:

+ +
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")
+
+ +

Si llama al método toString en el objeto personalizado, devuelve el valor predeterminado heredado de Object:

+ +
elPerro.toString() //devuelve [object Object]
+
+ +

El siguiente código crea y asigna perroToString para sobreescribir el método predeterminado toString. Esta función genera una cadena que contiene nombre, criadero, color, y sexo del objeto, en la forma "propiedad = valor;".

+ +
Perro.prototype.toString = function perroToString() {
+  var retorno = "Perro " + this.nombre + " es " + this.sexo + " " + this.color + " " + this.criadero;
+  return retorno;
+}
+
+ +

Con el código precedente en su lugar, cualquier vez que se use elDog en un contexto de una cadena, JavaScript automáticamente llamará a la función perroToString, la cuál devuelve la siguiente cadena:

+ +
Perro Gabby es femenino chocolate Laboratorio
+
+ +

Vea También

+ + 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 +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

El método valueOf() retorna el valor primitivo del objeto especificado.

+ +

Sintaxis

+ +
object.valueOf()
+ +

Valor de retorno

+ +

El valor primitivo del objeto especificado.

+ +

 

+ +

{{EmbedInteractiveExample("pages/js/object-prototype-valueof.html")}}

+ +

 

+ +

Descripción

+ +

JavaScript utiliza el método valueOf para convertir un objeto a un valor primitivo. Raramente usted necesitará invocar el método valueOf por su cuenta; JavaScript lo realizará de forma automática cuando encuentre un objeto, donde un valor primitivo es esperado.

+ +

Por defecto, el método valueOf es heredado por cada objeto descendiente de {{jsxref("Object")}}. 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, valueOf devuelve el objeto en sí.

+ +

Puede utilizar valueOf 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 Object.prototype.valueOf() para invocar un método personalizado, en vez de utilizar el método por defecto {{jsxref("Object")}}.

+ +

Sobreescribiendo valueOf para objetos personalizados

+ +

Puede crear una función para ser invocada en lugar de utilizar el método valueOf por defecto. Su función no debe contener ningún parámetro.

+ +

Suponga que tiene un objeto de tipo myNumberType y usted quiere crear un método valueOf para este. El código a continuación asigna una función personalizada al método valueOf:

+ +
myNumberType.prototype.valueOf = function() { return customPrimitiveValue; };
+ +

Al tener el código anterior funcionando, cada vez que un objeto de tipo myNumberType 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.

+ +

El método valueOf es invocado usualmente por JavaScript pero usted puede invocarlo directamente como sigue a continuación:

+ +
myNumber.valueOf()
+ +
+

Nota: Objetos en contextos de string realizan la conversión a string a través del método {{jsxref("Object.toString", "toString()")}} , el cual, es diferente de {{jsxref("String")}} para convertir objetos a primitivos string utilizando el método valueOf. Todos los objetos pueden ser convertidos a string, si solo "[object type]". Pero muchos objetos no se pueden convertir a number, boolean o function.

+
+ +

Ejemplos

+ +

Utilizando valueOf

+ +
function myNumberType(n) {
+    this.number = n;
+}
+
+myNumberType.prototype.valueOf = function() {
+    return this.number;
+};
+
+myObj = new myNumberType(4);
+myObj + 3; // 7
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoCommentario
ECMAScript 1ra Edición.EstándarDefinición inicial. Implementado en JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.2.4.4', 'Object.prototype.valueOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ES6')}} +

 

+
{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ESDraft')}}    
+ +

Compatibilidad con Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
ElementoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ElementoAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vea también

+ + 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 +--- +
{{JSRef}}
+ +

El método Object.values() devuelve un array con los valores correspondientes a las propiedades enumerables 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 for-in también enumera las propiedades en la cadena de prototipo de un objeto).

+ +

{{EmbedInteractiveExample("pages/js/object-values.html")}}

+ +

Sintaxis

+ +
Object.values(obj)
+ +

Parámetros

+ +
+
obj
+
Objeto cuyas propiedades enumerables serán devueltas.
+
+ +

Valor devuelto

+ +

Un array con las propiedades enumerables del objeto pasado como parámetro.

+ +

Descripción

+ +

El método Object.values() 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.

+ +

Ejemplos

+ +
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 se fuerzan a que se comporten como tal
+console.log(Object.values('foo')); // ['f', 'o', 'o']
+
+ +

Polyfill

+ +

Para dar soporte compatible con  Object.values() a entornos antiguos que no la soportan de forma nativa, puedes encontrar un Polyfill en tc39/proposal-object-values-entries o en los repositorios es-shims/Object.values.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}{{Spec2('ESDraft')}}Definición inicial.
{{SpecName('ES8', '#sec-object.values', 'Object.values')}}{{Spec2('ES8')}}
+ +

Compatibilidad en navegadores

+ +
{{Compat("javascript.builtins.Object.values")}}
+ +

Ver también

+ + -- cgit v1.2.3-54-g00ecf