diff options
Diffstat (limited to 'files/es/web/javascript/reference/global_objects/symbol')
4 files changed, 724 insertions, 0 deletions
diff --git a/files/es/web/javascript/reference/global_objects/symbol/for/index.html b/files/es/web/javascript/reference/global_objects/symbol/for/index.html new file mode 100644 index 0000000000..4af80e0072 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/symbol/for/index.html @@ -0,0 +1,154 @@ +--- +title: Symbol.for() +slug: Web/JavaScript/Reference/Global_Objects/Symbol/for +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/for +original_slug: Web/JavaScript/Referencia/Objetos_globales/Symbol/for +--- +<div>{{JSRef}}</div> + +<p>El método <code><strong>Symbol.for(key)</strong></code> busca símbolos existentes en el runtime global del registro de <em>symbols</em> con la <code>key</code> enviada cómo argumento y devuelve el symbol si fue encontrada. Sino, un nuevo symbol es creado en el registro global de <em>symbols </em>con dicha <code>key</code> .</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>Symbol.for(key)</var>;</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt>key</dt> + <dd>String, requirido. La <em>key </em>para el símbolo (y también usada para la descripción del <em>Symbol</em>).</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Un <em>Symbol </em>existente para la <em>key </em>enviada si se encuentra, un nuevo <em>Symbol</em> creado para la <em>key </em>si no es encontrado.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>A diferencia de <code>Symbol()</code>, la función <code>Symbol.for()</code> crea un symbol disponible el registro global de symbols.</p> + +<p>Sin embargo, <code>Symbol.for()</code> no crea un nuevo symbol en cada llamada: primero chequea si existe un symbol para la <code>key</code> en el registro y sólo crea un nuevo symbol si la <code>key</code> no es encontrada.</p> + +<p>El registro global de symbol es una lista con la siguiente estructura (inicializada vacía):</p> + +<table class="standard-table"> + <caption>Estructura registro global de symbol</caption> + <tbody> + <tr> + <th>Field name</th> + <th>Value</th> + </tr> + <tr> + <td>[[key]]</td> + <td>Un string usado como key para identifcar al símbolo.</td> + </tr> + <tr> + <td>[[symbol]]</td> + <td>El symbol que es guardado globalmente.</td> + </tr> + </tbody> +</table> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">Symbol.for('foo'); // crea un nuevo global symbol +Symbol.for('foo'); // devuelve el symbol creado + +// El mismo symbol global, pero no localmente +Symbol.for('bar') === Symbol.for('bar'); // true +Symbol('bar') === Symbol('bar'); // false + +// La key es usada en la descripción +var sym = Symbol.for('mario'); +sym.toString(); // "Symbol(mario)" +</pre> + +<p>Es una buena práctica agregar un prefijo a los symbols para evitar conflictos con otras librerias del código:</p> + +<pre class="brush: js">Symbol.for('mdn.foo'); +Symbol.for('mdn.bar'); +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-symbol.for', 'Symbol.for')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definición inicial</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.for', 'Symbol.for')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_entre_exploradores">Compatibilidad entre exploradores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(40) }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop("36.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>9</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("36.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Symbol.keyFor()")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/symbol/hasinstance/index.html b/files/es/web/javascript/reference/global_objects/symbol/hasinstance/index.html new file mode 100644 index 0000000000..c930685453 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/symbol/hasinstance/index.html @@ -0,0 +1,106 @@ +--- +title: Symbol.hasInstance +slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance +original_slug: Web/JavaScript/Referencia/Objetos_globales/Symbol/hasInstance +--- +<div>{{JSRef}}</div> + +<p>El bien conocido símbolo <strong><code>Symbol.hasInstance</code></strong> es usado para determinar si un constructor reconoce un objeto como su instancia. El comportamiento del operador {{jsxref("Operators/instanceof", "instanceof")}} puede ser personalizado con este símbolo.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Ejemplos">Ejemplos</h2> + +<p>Usted puede implementar un comportamiento personalizado para el operador <code>instanceof</code> tal que así:</p> + +<pre class="brush: js">class MyArray { + static [Symbol.hasInstance](instance) { + return Array.isArray(instance); + } +} +console.log([] instanceof MyArray); // true</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop(50) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile(50) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/symbol/index.html b/files/es/web/javascript/reference/global_objects/symbol/index.html new file mode 100644 index 0000000000..8279b2a8a7 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,365 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +original_slug: Web/JavaScript/Referencia/Objetos_globales/Symbol +--- +<div>{{JSRef}}</div> + +<p><em><strong>Symbol</strong></em> es un tipo de datos cuyos valores son únicos e immutables. Dichos valores pueden ser utilizados como identificadores (claves) de las propiedades de los objetos. Cada valor del tipo Symbol tiene asociado un valor del tipo String o Undefined que sirve únicamente como descripción del símbolo.</p> + +<p>La función <code>Symbol</code> {{Glossary("Primitive", "primitive data type")}} es el constructor de valores del tipo <em><strong>Symbol</strong></em>. Cuando <code>Symbol </code>es llamado como función nos devuelve una nuevo valor del tipo <em><strong>Symbol.</strong></em> El constructor <code>Symbol</code> no debe ser usado con el operador <code>new</code>. Tampoco debe ser extendido mediante clases.</p> + + + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><code>Symbol(<em>[description]</em>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>Descripcion</code> {{optional_inline}}</dt> + <dd>Es un valor opcional de tipo String. Únicamente sirve como descripción del símbolo que puede ser útil para depurar. No permite el acceso al símbolo que describe.</dd> +</dl> + +<h2 id="Descripción">Descripción</h2> + +<p>Para crear un nuevo símbolo, simplemente escribimos <code>Symbol()</code>, opcionalmente con un argumento de tipo String que constituiría la descripción del símbolo:</p> + +<pre class="brush: js">var sym1 = Symbol(); +var sym2 = Symbol("foo"); +var sym3 = Symbol("foo"); +</pre> + +<p>El código anterior crea tres símbolos nuevos. Hay que destacar que <code>Symbol("foo")</code> no convierte la cadena "foo" en un símbolo, sino que crea un símbolo nuevo que tiene la misma descripción.</p> + +<pre class="brush: js">Symbol("foo") === Symbol("foo"); // false</pre> + +<p>La siguiente sintaxis con el operador {{jsxref("Operators/new", "new")}} lanzará un {{jsxref("TypeError")}}:</p> + +<pre class="brush: js">var sym = new Symbol(); // TypeError</pre> + +<p>Esto evita la creación de un objeto envolvente explícito de Symbol en lugar de un nuevo valor de tipo símbolo. Si realmente se desea crear un <code>Symbol</code> wrapper object, podemos usar la función <code>Object()</code>:</p> + +<pre class="brush: js">var sym = Symbol("foo"); +typeof sym; // "symbol" +var symObj = Object(sym); +typeof symObj; // "object" +</pre> + +<h3 id="Símbolos_compartidos_en_el_registro_global_de_símbolos">Símbolos compartidos en el registro global de símbolos</h3> + +<p>La sintaxis anteriormente descrita que usa la función <code>Symbol()</code> no creara un símbolo global disponible para toda el código base. Para crear símbolos accesibles a través de los archivos incluso a través de <em>realms</em> (cada uno de los cuales tiene su propio <em>global scope</em>) es necesario utilizar los métodos {{jsxref("Symbol.for()")}} y {{jsxref("Symbol.keyFor()")}} para crear y acceder a los símbolos desde un registro global de valores del tipo <em>Symbol</em>.</p> + +<h3 id="Encontrando_las_claves_de_tipo_símbolo_de_un_objeto">Encontrando las claves de tipo símbolo de un objeto</h3> + +<p>El método {{jsxref("Object.getOwnPropertySymbols()")}} devuelve un <em>array</em> con los símbolos que sirven como claves de las propiedades propias de un objeto. Hay que destacar que cada objeto es inicializado sin propiedades propias con claves de tipo <em>Symbol</em>, así que este <em>array</em> estará vacio a menos que se hayan creado explicitamente propiedades con clave de tipo símbolo en el objeto.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt><code>Symbol.length</code></dt> + <dd>La propiedad <code>length</code> cuyo valor es 0 para todos los símbolos.</dd> + <dt>{{jsxref("Symbol.prototype")}}</dt> + <dd>Representa el prototipo constructor <code>Symbol</code>. Es un objeto ordinario.</dd> +</dl> + +<h3 id="Símbolos_bien_conocidos">Símbolos bien conocidos</h3> + +<p>JavaScript tiene algunos <em>símbolos incorporados</em> que representan comportamientos internos del lenguaje que no fueron expuestos a los programadores antes de ECMAScript 6. Se accede a los dichos símbolos a través de las siguientes propiedades del constructor <code>Symbol.</code></p> + +<h4 id="Símbolo_de_iteración">Símbolo de iteración</h4> + +<dl> + <dt>{{jsxref("Symbol.iterator")}}</dt> + <dd>Los objetos que implementen la interfaz <em><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface">Iterable</a></em> deben tener una propiedad que tenga como clave este símbolo. Dicha propiedad debe ser una función que devuelva un objeto que implemente la interfaz <em><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface">Iterator</a></em>. Usado por <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for...of</code></a>.</dd> +</dl> + +<h4 id="Símbolos_de_expresiones_regulares">Símbolos de expresiones regulares</h4> + +<dl> + <dt>{{jsxref("Symbol.match")}}</dt> + <dd>Un método que iguala a un String, también usado para determinar si un objeto puede ser usado como una expresión regular. Usado por {{jsxref("String.prototype.match()")}}.</dd> + <dt>{{jsxref("Symbol.replace")}}</dt> + <dd>Un método que reemplaza las subcadenas que coinciden con una cadena. Utilizado por {{jsxref("String.prototype.replace()")}}.</dd> + <dt>{{jsxref("Symbol.search")}}</dt> + <dd>Un método que devuelve el índice dentro de una cadena que coincide con la expresión regular. Utilizado por {{jsxref("String.prototype.search()")}}.</dd> + <dt>{{jsxref("Symbol.split")}}</dt> + <dd>Un método que separa una cadena en los índices que coincide una expresión regular. Utilizado por {{jsxref("String.prototype.split()")}}.</dd> +</dl> + +<h4 id="Otros_símbolos">Otros símbolos</h4> + +<dl> + <dt>{{jsxref("Symbol.hasInstance")}}</dt> + <dd>Un método que determina si un objeto constructor reconoce al objeto como su instancia. Utilizado por {{jsxref("Operators/instanceof", "instanceof")}}.</dd> + <dt>{{jsxref("Symbol.isConcatSpreadable")}}</dt> + <dd>Un valor booleano que indica si un objeto debe ser aplanado a sus elementos de matriz. Usado por {{jsxref("Array.prototype.concat()")}}.</dd> + <dt>{{jsxref("Symbol.unscopables")}}</dt> + <dd>An Array of string values that are property values. These are excluded from the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code> environment bindings of the associated objects.</dd> + <dt>{{jsxref("Symbol.species")}}</dt> + <dd>Una función <code>constructor</code> utilizada para crear objetos derivados.</dd> + <dt>{{jsxref("Symbol.toPrimitive")}}</dt> + <dd>Un método para convertir un objeto a su valor primitivo.</dd> + <dt>{{jsxref("Symbol.toStringTag")}}</dt> + <dd>Un método para definir la descripción por defecto de un objeto. Usado por {{jsxref("Object.prototype.toString()")}}.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Symbol.for()", "Symbol.for(key)")}}</dt> + <dd>Searches for existing symbols with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.</dd> + <dt>{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}</dt> + <dd>Retrieves a shared symbol key from the global symbol registry for the given symbol.</dd> +</dl> + +<h2 id="Symbol_prototype"><code>Symbol</code> prototype</h2> + +<p>All Symbols inherit from {{jsxref("Symbol.prototype")}}.</p> + +<h3 id="Propiedades_2">Propiedades</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}</p> + +<h3 id="Métodos_2">Métodos</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Usando_el_operador_typeof_con_symbols">Usando el operador <code>typeof</code> con symbols</h3> + +<p>El operador {{jsxref("Operators/typeof", "typeof")}} puede ayudar a identificar los Symbol.</p> + +<pre class="brush: js">typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' +</pre> + +<h3 id="Symbol_type_conversions">Symbol type conversions</h3> + +<p>Some things to note when working with type conversion of symbols.</p> + +<ul> + <li>When trying to convert a symbol to a number, a {{jsxref("TypeError")}} will be thrown<br> + (e.g. <code>+sym</code> or <code>sym | 0</code>).</li> + <li>When using loose equality, <code>Object(sym) == sym</code> returns <code>true.</code></li> + <li><code>Symbol("foo") + "bar" </code>throws a {{jsxref("TypeError")}} (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example.</li> + <li>The <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion">"safer" <code>String(sym)</code> conversion</a> works like a call to {{jsxref("Symbol.prototype.toString()")}} with symbols, but note that <code>new String(sym)</code> will throw.</li> +</ul> + +<h3 id="Symbols_y_el_iterador_for...in">Symbols y el iterador <code>for...in</code></h3> + +<p>Symbols are not visible in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> iterations. In addition, {{jsxref("Object.getOwnPropertyNames()")}} will not return symbol object properties, however, you can use {{jsxref("Object.getOwnPropertySymbols()")}} to get these.</p> + +<pre class="brush: js">var obj = {}; + +obj[Symbol("a")] = "a"; +obj[Symbol.for("b")] = "b"; +obj["c"] = "c"; +obj.d = "d"; + +for (var i in obj) { + console.log(i); // logs "c" and "d" +}</pre> + +<h3 id="Symbols_y_JSON.stringify()">Symbols y <code>JSON.stringify()</code></h3> + +<p>Symbol-keyed properties will be completely ignored when using <code>JSON.stringify()</code>:</p> + +<pre class="brush: js">JSON.stringify({[Symbol("foo")]: "foo"}); +// '{}'</pre> + +<p>For more details, see {{jsxref("JSON.stringify()")}}.</p> + +<h3 id="Symbol_wrapper_objects_as_property_keys">Symbol wrapper objects as property keys</h3> + +<p>When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:</p> + +<pre class="brush: js">var sym = Symbol("foo"); +var obj = {[sym]: 1}; +obj[sym]; // 1 +obj[Object(sym)]; // still 1 +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop("36.0")}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.iterator (@@iterator)</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop("36.0")}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.unscopables (@@unscopables)</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.match (@@match)</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("40.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Symbol.species (@@species)</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("41.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Symbol.toPrimitive (@@toPrimitive)</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("44.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Other well-known symbols</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{ CompatGeckoMobile("36.0") }}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.iterator (@@iterator)</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{ CompatGeckoMobile("36.0") }}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.unscopables (@@unscopables)</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.match (@@match)</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("40.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Symbol.species (@@species)</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("41.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Symbol.toPrimitive (@@toPrimitive)</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Other well-known symbols</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Mira_también">Mira también</h2> + +<ul> + <li><a href="/en-US/docs/Glossary/Symbol">Glossary: Symbol data type</a></li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/">"ES6 In Depth: Symbols" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/es/web/javascript/reference/global_objects/symbol/iterator/index.html b/files/es/web/javascript/reference/global_objects/symbol/iterator/index.html new file mode 100644 index 0000000000..7638e3e4e3 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/symbol/iterator/index.html @@ -0,0 +1,99 @@ +--- +title: Symbol.iterator +slug: Web/JavaScript/Reference/Global_Objects/Symbol/iterator +tags: + - ECMAScript6 + - JavaScript + - Property + - Symbol +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/iterator +original_slug: Web/JavaScript/Referencia/Objetos_globales/Symbol/iterator +--- +<div>{{JSRef}}</div> + +<p>El símbolo <code><strong>Symbol.iterator</strong></code> especifica al iterador por defecto de un objeto. Es utilizado por el bucle {{jsxref("Sentencias/for","for")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/symbol-iterator.html")}}</div> + +<p class="hidden">El código fuente de este ejemplo interactivo está guardado en un repositorio en GitHub. Si quieres contribuir al proyecto de ejemplos interactivos, por favor clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> y envía un pull request.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Descripción">Descripción</h2> + +<p>En cualquier situación donde se necesita iterar un objeto (por ejemplo al inicio de un bucle <code>for..of</code>), su método <code>@@iterator</code> es invocado sin argumentos, y el <strong>iterador</strong> regresado es utilizador para obtener los valores a iterar.</p> + +<p>Algunos tipos integrados cuentan con un comportamiento de iterar por defecto, mientras que otros tipos (como {{jsxref("Object")}}) no. Los tipos integrados con un método <code>@@iterator</code> son:</p> + +<ul> + <li>{{jsxref("Array.@@iterator", "Array.prototype[@@iterator]()")}}</li> + <li>{{jsxref("TypedArray.@@iterator", "TypedArray.prototype[@@iterator]()")}}</li> + <li>{{jsxref("String.@@iterator", "String.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Set.@@iterator", "Set.prototype[@@iterator]()")}}</li> +</ul> + +<p>Ver <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Protocolos de iteración</a> para más información.</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Iterables_definidos_por_el_usuario">Iterables definidos por el usuario</h3> + +<p>Podemos definir nuestros propios iterables de la siguiente forma:</p> + +<pre class="brush: js notranslate">var myIterable = {} +myIterable[Symbol.iterator] = function* () { + yield 1; + yield 2; + yield 3; +}; +[...myIterable] // [1, 2, 3] +</pre> + +<h3 id="Iterables_mal_formados">Iterables mal formados</h3> + +<p>Si un método iterador <code>@@iterator</code> no devuelve un objeto iterador, es un iterable mal formado. Usarlo como tal es probable que genere excepciones en tiempo de ejecución, o comportamientos inesperados.</p> + +<pre class="brush: js notranslate">var nonWellFormedIterable = {} +nonWellFormedIterable[Symbol.iterator] = () => 1 +[...nonWellFormedIterable] // TypeError: [] is not a function +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificaciób</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-symbol.iterator', 'Symbol.iterator')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.iterator', 'Symbol.iterator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + + + +<p>{{Compat("javascript.builtins.Symbol.iterator")}}</p> + +<h2 id="Temas_relacionados">Temas relacionados</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> + <li>{{jsxref("Array.@@iterator", "Array.prototype[@@iterator]()")}}</li> + <li>{{jsxref("TypedArray.@@iterator", "TypedArray.prototype[@@iterator]()")}}</li> + <li>{{jsxref("String.@@iterator", "String.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Set.@@iterator", "Set.prototype[@@iterator]()")}}</li> +</ul> |
