diff options
author | Ryan Johnson <rjohnson@mozilla.com> | 2021-04-29 16:16:42 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-29 16:16:42 -0700 |
commit | 95aca4b4d8fa62815d4bd412fff1a364f842814a (patch) | |
tree | 5e57661720fe9058d5c7db637e764800b50f9060 /files/it/web/javascript/reference/operators | |
parent | ee3b1c87e3c8e72ca130943eed260ad642246581 (diff) | |
download | translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.gz translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.bz2 translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.zip |
remove retired locales (#699)
Diffstat (limited to 'files/it/web/javascript/reference/operators')
10 files changed, 0 insertions, 2406 deletions
diff --git a/files/it/web/javascript/reference/operators/comma_operator/index.html b/files/it/web/javascript/reference/operators/comma_operator/index.html deleted file mode 100644 index f4cf7b3fd6..0000000000 --- a/files/it/web/javascript/reference/operators/comma_operator/index.html +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Operatore virgola -slug: Web/JavaScript/Reference/Operators/Comma_Operator -translation_of: Web/JavaScript/Reference/Operators/Comma_Operator -original_slug: Web/JavaScript/Reference/Operators/Operatore_virgola ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>L'<strong>operatore virgola</strong> valuta ciascuno dei suoi operandi, da sinistra a destra, e restituisce il valore dell'ultimo operando.</p> - -<div>{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><em>expr1</em>, <em>expr2, expr3...</em></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>expr1</code>, <code>expr2</code>, <code>expr3</code>...</dt> - <dd>Qualsiasi espressione.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Puoi utilizzare l'operatore virgola quando vuoi includere più espressioni in una posizione che richiede una singola espressione. L'uso più comune di questo operatore è di fornire più parametri in un ciclo <code>for</code>.</p> - -<p>L'operatore virgola è completamente differente dalla virgola utilizzata negli array, negli oggetti, e negli argomenti e parametri di funzione.</p> - -<h2 id="Esempi">Esempi</h2> - -<p>Considerando <code>a</code> un array di 2 dimensioni contenente 10 elementi per ciascun lato, il seguente codice utilizza l'operatore virgola per incrementare <code>i</code> e decrementare <code>j</code> contemporaneamente.</p> - -<p>Il seguente codice stampa i valori degli elementi in posizione diagonale dell'array:</p> - -<pre class="brush:js;highlight:[1]">for (var i = 0, j = 9; i <= 9; i++, j--) - console.log('a[' + i + '][' + j + '] = ' + a[i][j]);</pre> - -<p>Si noti che gli operatori virgola nelle assegnazioni potrebbero non avere l'effetto normale degli operatori virgola perché non esistono all'interno di un'espressione. Nel seguente esempio, <code>a</code> é impostato al valore di <code>b = 3</code> (che é 3), ma l'espressione <code>c = 4</code> continua a essere valutata e il suo valore viene restituito alla console (cioé 4). Questo é dovuto alla <a href="/it/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">precedenza e all'associtività dell'operatore</a>.</p> - -<pre class="brush: js">var a, b, c; - -a = b = 3, c = 4; // restituisce 4 nella console -console.log(a); // 3 (più a sinistra) - -var x, y, z; - -x = (y = 5, z = 6); // restituisce 6 nella console -console.log(x); // 6 (più a destra) -</pre> - -<h3 id="Elaborazione_e_restituzione">Elaborazione e restituzione</h3> - -<p>Un altro esempio che si potrebbe fare con l'operatore virgola è quello di eleborare prima di restituire. Come detto, solo l'ultimo elemento viene restituito ma anche tutti gli altri vengono valutati. Quindi, si potrebbe fare:</p> - -<pre class="brush: js">function myFunc() { - var x = 0; - - return (x += 1, x); // stesso comportamento di ++x; -}</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-comma-operator', 'Comma operator')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11.14', 'Comma operator')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES1', '#sec-11.14', 'Comma operator')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.operators.comma")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/it/docs/Web/JavaScript/Reference/Statements/for"><code>for</code> loop</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/conditional_operator/index.html b/files/it/web/javascript/reference/operators/conditional_operator/index.html deleted file mode 100644 index 1d0bc7f79a..0000000000 --- a/files/it/web/javascript/reference/operators/conditional_operator/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Operatore condizionale (ternary) -slug: Web/JavaScript/Reference/Operators/Conditional_Operator -tags: - - JavaScript Operatore operatore -translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator -original_slug: Web/JavaScript/Reference/Operators/Operator_Condizionale ---- -<p>L'<strong>operator</strong><strong>e</strong><strong> condizionale (ternary) </strong>è l'unico operatore JavaScript che necessità di tre operandi. Questo operatore è frequentemente usato al posto del comando <a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if</code></a> per la sua sintassi concisa e perché fornisce direttamente un espressione valutabile.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><em>condizione</em> ? <em>espressione1</em> : <em>espressione2</em> </pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>condizione</code></dt> - <dd>Un espressione booleana (che viene valutata in vero o <code>falso)</code>.</dd> -</dl> - -<dl> - <dt><code>espressione1</code>, <code>espressione2</code></dt> - <dd>Espressione di qualunque tipo (vedi avanti nella pagina).</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Se <code>la condizione è vera</code>, l'operatore ritorna il valore di <code>espressione1</code>; altrimenti, ritorna il valore di <code>espressione2</code>. Per esempio, puoi usare questa espressione per mostrare un messaggio che cambia in base al valore della variabile <strong><code>isMember</code></strong>:</p> - -<pre class="brush: js">"The fee is " + (isMember ? "$2.00" : "$10.00") -</pre> - -<p>Puoi anche assegnare variabili dipendenti dal risultato di un operatore ternario:</p> - -<pre class="brush: js">var elvisLives = Math.PI > 4 ? "Yep" : "Nope";</pre> - -<p>Sono anche possibili espressioni con operatori ternari multipli (nota: l'operatore condizionale è associativo a destra):</p> - -<pre class="brush: js">var firstCheck = false, - secondCheck = false, - access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted"; - -console.log( access ); // logs "Access granted"</pre> - -<p>Puoi anche usare l'operatore ternario direttamente senza assegnamenti e senza combinazioni con altre espressioni, con lo scopo di valutare operazioni alternative:</p> - -<pre class="brush: js">var stop = false, age = 16; - -age > 18 ? location.assign("continue.html") : stop = true; -</pre> - -<p>Puoi anche valutare operazioni multiple separandole con delle virgole:</p> - -<pre class="brush: js">var stop = false, age = 23; - -age > 18 ? ( - alert("OK, you can go."), - location.assign("continue.html") -) : ( - stop = true, - alert("Sorry, you are much too young!") -); -</pre> - -<p>Puoi anche valutare più operazioni durante l'assegnamento di una variabile. In questo caso, <strong>l'ultimo valore separato da una virgola nelle parentesi sarà il valore assegnato</strong>.</p> - -<pre class="brush: js">var age = 16; - -var url = age > 18 ? ( - alert("OK, you can go."), - // alert returns "undefined", but it will be ignored because - // isn't the last comma-separated value of the parenthesis - "continue.html" // the value to be assigned if age > 18 -) : ( - alert("You are much too young!"), - alert("Sorry :-("), - // etc. etc. - "stop.html" // the value to be assigned if !(age > 18) -); - -location.assign(url); // "stop.html"</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_Browser">Compatibilità con Browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if statement</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/destructuring_assignment/index.html b/files/it/web/javascript/reference/operators/destructuring_assignment/index.html deleted file mode 100644 index 12a790e45c..0000000000 --- a/files/it/web/javascript/reference/operators/destructuring_assignment/index.html +++ /dev/null @@ -1,451 +0,0 @@ ---- -title: Assegnamento di destrutturazione -slug: Web/JavaScript/Reference/Operators/Destructuring_assignment -translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>La sintassi di <strong>assegnamento di destrutturazione </strong>è un'espressione JavaScript che rende possibile estrarre informazioni da array o oggetti in variabili distinte.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="brush:js">var a, b, rest; -[a, b] = [1, 2]; -console.log(a); // 1 -console.log(b); // 2 - -[a, b, ...rest] = [1, 2, 3, 4, 5]; -console.log(a); // 1 -console.log(b); // 2 -console.log(rest); // [3, 4, 5] - -({a, b} = {a:1, b:2}); -console.log(a); // 1 -console.log(b); // 2 - -// ES2016 - non implementato in Firefox 47a01 -({a, b, ...rest} = {a:1, b:2, c:3, d:4}); -</pre> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Le espressioni lettali degli oggetti e degli array forniscono un modo facile per creare <em>ad hoc</em> pacchetti di data.</p> - -<pre class="brush: js">var x = [1, 2, 3, 4, 5];</pre> - -<p>L'assegnamento di destrutturazione utilizza una sintassi simile, ma a sinistra dell'assegnamento sono definiti quali elementi estrarre dalla variabile sorgente (array o oggetti).</p> - -<pre class="brush: js">var x = [1, 2, 3, 4, 5]; -var [y, z] = x; -console.log(y); // 1 -console.log(z); // 2 -</pre> - -<p>Questa capacità è simile alle caratteristiche presenti in linguaggi come Perl e Python.</p> - -<h2 id="Destrutturazione_di_array">Destrutturazione di array</h2> - -<h3 id="Assegnamento_semplice_di_variabile">Assegnamento semplice di variabile</h3> - -<pre class="brush: js">var foo = ["one", "two", "three"]; - -var [one, two, three] = foo; -console.log(one); // "one" -console.log(two); // "two" -console.log(three); // "three" -</pre> - -<h3 id="Assegnamento_separato_dalla_dichiarazione">Assegnamento separato dalla dichiarazione</h3> - -<p>Il valore di una variabile può essere assegnato (sempre con la destrutturazione) in modo separato dalla dichiarazione della variabile stessa.</p> - -<pre class="brush:js">var a, b; - -[a, b] = [1, 2]; -console.log(a); // 1 -console.log(b); // 2 -</pre> - -<h3 id="Valori_default">Valori default</h3> - -<p>Ad una variabile può essere assegnato un valore default nel caso in cui il valore estratto dall'array sia <code>undefined</code>.</p> - -<pre class="brush: js">var a, b; - -[a=5, b=7] = [1]; -console.log(a); // 1 -console.log(b); // 7 -</pre> - -<h3 id="Scambio_di_variabili">Scambio di variabili</h3> - -<p>Due valori di variabili possono essere scambiati in un assegnamento di destrutturazione.</p> - -<p>Senza l'assegnamento di destrutturazione, scambiare due valori richiede una variabile momentanea (o, in alcuni linguaggi low-level, il <a class="external" href="https://en.wikipedia.org/wiki/XOR_swap_algorithm">XOR-swap trick</a>).</p> - -<pre class="brush:js">var a = 1; -var b = 3; - -[a, b] = [b, a]; -console.log(a); // 3 -console.log(b); // 1 -</pre> - -<h3 id="Fare_il_parsing_di_un_array_ritornato_da_una_funzione">Fare il parsing di un array ritornato da una funzione</h3> - -<p>È sempre stato possibile ritornare un array da una funzione. La destrutturazione può rendere più conciso lavorare con il valore di ritorno di un array</p> - -<p>In questo esempio, <code>f()</code> ritorna i valori <code>[1, 2]</code> come output, e questi possono essere analizzati in una singola linea con la destrutturazione.</p> - -<pre class="brush:js">function f() { - return [1, 2]; -} - -var a, b; -// puoi fare questo grazie alla destrutturazione -[a, b] = f(); - -// invece di questo -a = f()[0]; -b = f()[1]; - -// è la stessa identica cosa, però c'è un enorme differenza in termini -//di leggibilità e concisione - -console.log(a); // 1 -console.log(b); // 2 -</pre> - -<h3 id="Ignorare_alcuni_valori_ritornati">Ignorare alcuni valori ritornati</h3> - -<p>Puoi ignorare i valori ritornati nei quali non sei interessato:</p> - -<pre class="brush:js">function f() { - return [1, 2, 3]; -} - -var [a, , b] = f(); -console.log(a); // 1 -console.log(b); // 3 -</pre> - -<p>Puoi anche ignorare tutti i valori ritornati:</p> - -<pre class="brush:js">[,,] = f(); -</pre> - -<h3 id="Assegnare_il_resto_di_un_array_ad_una_variabile">Assegnare il resto di un array ad una variabile</h3> - -<p>Quando si destruttura un array, puoi assegnare la sua parte rimanente ad una variabile usando l'operatore rest (i 3 puntini):</p> - -<pre class="brush: js">var [a, ...b] = [1, 2, 3]; -console.log(a); // 1 -console.log(b); // [2, 3]</pre> - -<h3 id="Estrarre_valori_da_un_match_con_un'espressione_regolare">Estrarre valori da un match con un'espressione regolare</h3> - -<p>Quando il metodo <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">exec()</a></code> trova un match, ritorna un array contenente come 1° elemento l'intera porzione della stringa e poi le porzioni della stringa che hanno fatto match con ognuno dei gruppi in parentesi dell'espressione regolare. L'assegnamento di destrutturazione ti permetti di estrarre le parti di questo array facilmente, ignorando l'intero match se non ne hai bisogno.</p> - -<pre class="brush:js">var url = "https://developer.mozilla.org/en-US/Web/JavaScript"; - -var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); -console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] - -var [, protocol, fullhost, fullpath] = parsedURL; - -console.log(protocol); // "https" -</pre> - -<h2 id="Destrutturazione_degli_oggetti">Destrutturazione degli oggetti</h2> - -<h3 id="Assegnamento_base">Assegnamento base</h3> - -<pre class="brush: js">var o = {p: 42, q: true}; -var {p, q} = o; - -console.log(p); // 42 -console.log(q); // true -</pre> - -<h3 id="Assegnamento_senza_dichiarazione">Assegnamento senza dichiarazione</h3> - -<p>Il valore di una variabile può essere assegnato senza destrutturazione separatamente dalla sua dichiarazione.</p> - -<pre class="brush:js">var a, b; - -({a, b} = {a:1, b:2});</pre> - -<div class="note"> -<p><code><font face="Open Sans, Arial, sans-serif">Le </font>( )</code> attorno l'assegnamento di destrutturazione sono obbligatorie quando si usa la destrutturazione degli oggetti letterali senza una dichiarazione.</p> - -<p><code>{a, b} = {a:1, b:2}</code> non è sintassi valida, dato che <code>{a, b}</code> sulla sinistra è considerato un blocco e non un oggetto letterale.</p> - -<p>Tuttavia, <code>({a, b} = {a:1, b:2})</code> è valida, dato che <code>var {a, b} = {a:1, b:2}</code></p> -</div> - -<h3 id="Assegnamento_a_nuovi_nomi_di_variabili">Assegnamento a nuovi nomi di variabili </h3> - -<p>Una variabile può essere estratta da un oggetto e assegnata ad una variabile con un nome diverso da quello della proprietà dell'oggetto.</p> - -<pre class="brush: js">var o = {p: 42, q: true}; -var {p: foo, q: bar} = o; - -console.log(foo); // 42 -console.log(bar); // true </pre> - -<h3 id="Valori_default_2">Valori default</h3> - -<p>Ad una variabile può essere assegnato un valore default nel caso in cui il valore estratto dall'oggetto sia <code>undefined</code>.</p> - -<pre class="brush: js">var {a=10, b=5} = {a: 3}; - -console.log(a); // 3 -console.log(b); // 5</pre> - -<h3 id="Impostare_i_valore_default_dei_parametri_di_una_funzione">Impostare i valore default dei parametri di una funzione</h3> - -<h4 id="Versione_ES5">Versione ES5</h4> - -<pre class="brush: js">function drawES5Chart(options) { - options = options === undefined ? {} : options; - var size = options.size === undefined ? 'big' : options.size; - var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords; - var radius = options.radius === undefined ? 25 : options.radius; - console.log(size, cords, radius); - // now finally do some chart drawing -} - -drawES5Chart({ - cords: { x: 18, y: 30 }, - radius: 30 -});</pre> - -<h4 id="Versione_ES2015">Versione ES2015</h4> - -<pre class="brush: js">function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) { - console.log(size, cords, radius); - // do some chart drawing -} - -drawES2015Chart({ - cords: { x: 18, y: 30 }, - radius: 30 -});</pre> - -<h3 id="Oggetti_annidati_e_destrutturazione_array">Oggetti annidati e destrutturazione array</h3> - -<pre class="brush:js">var metadata = { - title: "Scratchpad", - translations: [ - { - locale: "de", - localization_tags: [ ], - last_edit: "2014-04-14T08:43:37", - url: "/de/docs/Tools/Scratchpad", - title: "JavaScript-Umgebung" - } - ], - url: "/en-US/docs/Tools/Scratchpad" -}; - -var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata; - -console.log(englishTitle); // "Scratchpad" -console.log(localeTitle); // "JavaScript-Umgebung"</pre> - -<h3 id="Iterazione_con_for...of_e_destrutturazione">Iterazione con for...of e destrutturazione</h3> - -<pre class="brush: js">var people = [ - { - name: "Mike Smith", - family: { - mother: "Jane Smith", - father: "Harry Smith", - sister: "Samantha Smith" - }, - age: 35 - }, - { - name: "Tom Jones", - family: { - mother: "Norah Jones", - father: "Richard Jones", - brother: "Howard Jones" - }, - age: 25 - } -]; - -for (var {name: n, family: { father: f } } of people) { - console.log("Name: " + n + ", Father: " + f); -} - -// "Name: Mike Smith, Father: Harry Smith" -// "Name: Tom Jones, Father: Richard Jones"</pre> - -<h3 id="Estrarre_campi_dagli_oggetti_passati_come_parametri_delle_funzioni">Estrarre campi dagli oggetti passati come parametri delle funzioni</h3> - -<pre class="brush:js">function userId({id}) { - return id; -} - -function whois({displayName: displayName, fullName: {firstName: name}}){ - console.log(displayName + " is " + name); -} - -var user = { - id: 42, - displayName: "jdoe", - fullName: { - firstName: "John", - lastName: "Doe" - } -}; - -console.log("userId: " + userId(user)); // "userId: 42" -whois(user); // "jdoe is John"</pre> - -<p>Questo estrae <code>id</code>, <code>displayName</code> e <code>firstName</code> da l'oggetto user e li stampa.</p> - -<h3 id="Proprietà_calcolate_degli_oggetti_e_destrutturazione">Proprietà calcolate degli oggetti e destrutturazione</h3> - -<p>I nomi delle proprietà calcolate degli oggetti, come sugli <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">object literals</a>, possono anche essere usate con la destrutturazione.</p> - -<pre class="brush: js">let key = "z"; -let { [key]: foo } = { z: "bar" }; - -console.log(foo); // "bar" -</pre> - -<h2 id="Specificazioni">Specificazioni</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-destructuring-assignment', 'Destructuring assignment')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Caratteristica</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Edge</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatChrome(49.0)}}</td> - <td>{{ CompatGeckoDesktop("1.8.1") }}</td> - <td>14</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>7.1</td> - </tr> - <tr> - <td>Nomi delle proprietà calcolate</td> - <td>{{CompatChrome(49.0)}}</td> - <td>{{ CompatGeckoDesktop("34") }}</td> - <td>14</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>Operatore spread</td> - <td>{{CompatChrome(49.0)}}</td> - <td>{{ CompatGeckoDesktop("34") }}</td> - <td>12<sup>[1]</sup></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Caratteristica</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> - <th>Chrome for Android</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(49.0)}}</td> - <td>{{ CompatGeckoMobile("1.0") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - <td>{{CompatChrome(49.0)}}</td> - </tr> - <tr> - <td>Nomi delle proprietà calcolate</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(49.0)}}</td> - <td>{{ CompatGeckoMobile("34") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(49.0)}}</td> - </tr> - <tr> - <td>Operatore spread</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(49.0)}}</td> - <td>{{ CompatGeckoMobile("34") }}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatChrome(49.0)}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Richiede "Attiva le caratteristiche sperimentali di JavaScript" per essere abilitato sotto `about:flags`</p> - -<h2 id="Note_specifiche_a_Firefox">Note specifiche a Firefox</h2> - -<ul> - <li>Firefox fornisce un'estensione del linguaggio non standard in <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JS1.7</a> per</li> - <li>la destrutturazione. Questa estensione è stata rimossa in Gecko 40 {{geckoRelease(40)}}. Vedi {{bug(1083498)}}.</li> - <li>Partendo con Gecko 41 {{geckoRelease(41)}} e per soddisfare le specifiche ES2015, gli schemi di destrutturazioni con le parentesi come <code>([a, b]) = [1, 2]</code> or <code>({a, b}) = { a: 1, b: 2 } </code>sono ora considerate invalide e quindi lanceranno un errore {{jsxref("SyntaxError")}}. Vedi <a class="external external-icon" href="http://whereswalden.com/2015/06/20/new-changes-to-make-spidermonkeys-and-firefoxs-parsing-of-destructuring-patterns-more-spec-compliant/">Jeff Walden's blog post</a> e {{bug(1146136)}} per ulteriori dettagli.</li> -</ul> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Operatori di assegnamento</a></li> - <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/">"ES2015 in profondità: Destrutturazioni" su hacks.mozilla.org</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/in/index.html b/files/it/web/javascript/reference/operators/in/index.html deleted file mode 100644 index d6dcb196de..0000000000 --- a/files/it/web/javascript/reference/operators/in/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: operatore in -slug: Web/JavaScript/Reference/Operators/in -tags: - - JavaScript - - Operatori - - Operatori Relazionali -translation_of: Web/JavaScript/Reference/Operators/in ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>L' operatore <strong><code>in</code> </strong>dà come ritorno <code>true</code> se la proprietà specificata si trova nell'oggetto preso in considerazione.</p> - -<p>Restituisce <code>false</code> se la proprietà è stata eliminata tramite <code>delete</code> ma non nel caso in cui sia stata inizializzata <code>undefined</code> dal programmatore.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><em>prop</em> in <em>nomeOggetto</em></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>prop</code></dt> - <dd>Una stringa o simbolo che rappresenta il nome di una proprietà o indice di un array (i non-simboli verranno automaticamente convertiti in stringhe).</dd> -</dl> - -<dl> - <dt><code>nomeOggetto</code></dt> - <dd>Nome di un oggetto.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>I seguenti esempi mostrano alcuni usi dell'operatore <code>in</code>.</p> - -<pre class="brush:js">// Array -var alberi = ["sequoia", "lauro", "cedro", "quercia", "acero"]; -0 in alberi // ritorna true -3 in alberi // ritorna true -6 in alberi // ritorna false, non ci sono proprietà in quell'indice su <em>alberi</em> -"bay" in alberi // ritorna false (devi specificare il - // numero dell'indice, non il valore corrispondente a quell'indice) -"length" in alberi // ritorna true (length è una proprietà degli array) -Symbol.iterator in alberi // ritorna true (gli array sono iterabili, funziona solo in ES6+) - -// Oggetti predefiniti -"PI" in Math // ritorna true, "PI" è il nome di una proprietà dell'oggetto Math - -// Oggetti personalizzati -var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998}; -"marca" in miaAuto // ritorna true -"modello" in miaAuto // ritorna true -</pre> - -<p>Devi specificare un oggetto sul lato destro dell'operatore <code>in</code>. Per esempio, puoi specificare una stringa creata con il costruttore String, ma non puoi specificare una stringa literal.</p> - -<pre class="brush:js">var colore1 = new String("verde"); -"length" in colore1 // ritorna true - -var color2 = "coral"; -// genera un errore (colore2 non è un oggetto String) -"length" in colore2 -</pre> - -<h3 id="Usare_l'operatore_in_con_le_proprietà_deleted_o_undefined">Usare l'operatore <code>in</code> con le proprietà deleted o undefined</h3> - -<p>Se elimini una proprietà con l'operatore <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete">delete</a></code>, l'operatore in ritorna <code>false</code> per quella proprietà.</p> - -<pre class="brush:js">var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998}; -delete miaAuto.marca; -"marca" in miaAuto; // ritorna false - -var alberi = new Array("sequoia", "lauro", "cedro", "quercia", "acero"); -delete alberi[3]; -3 in alberti; // ritorna false -</pre> - -<p>Se setti una proprietà ad {{jsxref("Global_Objects/undefined", "undefined")}} ma non la cancelli, l'operatore <code>in</code> darà come ritorno true per quella proprietà.</p> - -<pre class="brush:js">var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998}; -miaAuto.marca = undefined; //inizializzo manualmente la proprietà '<em>marca'</em> undefined -"marca" in miaAuto; // ritorna true, non è stato usato usato delete sulla proprietà -delete miaAuto.marca; -"marca" in miaAuto // return false, è stata eliminata la proprietà</pre> - -<p> </p> - -<p> </p> - -<p> </p> - -<pre class="brush:js">var alberi = new Array("sequoia", "lauro", "cedro", "quercia", "acero"); -alberi[3] = undefined; -3 in alberi; // ritorna true -</pre> - -<h3 id="Proprietà_ereditate">Proprietà ereditate</h3> - -<p>L'operatore <code>in</code> ritorna <code>true</code> per proprietà ereditate tramite prototipi.</p> - -<pre class="brush:js">"toString" in {}; // returns true -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11.8.7', 'The in Operator')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES3', '#sec-11.8.7', 'The in Operator')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.4.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</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>Edge</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code></li> - <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete">delete</a></code></li> - <li>{{jsxref("Object.prototype.hasOwnProperty()")}}</li> - <li>{{jsxref("Reflect.has()")}}</li> - <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties" title="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/index.html b/files/it/web/javascript/reference/operators/index.html deleted file mode 100644 index 9e257e3038..0000000000 --- a/files/it/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,282 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - NeedsTranslation - - Operators - - TopicStub -translation_of: Web/JavaScript/Reference/Operators ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>Questo capitolo documenta tutti gli operatori, espressioni e parole chiave del linguaggio JavaScript.</p> - -<h2 id="Espressioni_e_operatori_per_categoria">Espressioni e operatori per categoria</h2> - -<p>Per la lista alfabetica consultare la sidebar di sinistra</p> - -<h3 id="Espressioni_Primarie">Espressioni Primarie</h3> - -<p>Basic keywords and general expressions in JavaScript.</p> - -<dl> - <dt>{{jsxref("Operators/this", "this")}}</dt> - <dd>The <code>this</code> keyword refers to the function's execution context.</dd> - <dt>{{jsxref("Operators/function", "function")}}</dt> - <dd>The <code>function</code> keyword defines a function expression.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/class", "class")}}</dt> - <dd>The <code>class</code> keyword defines a class expression.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}</dt> - <dd>The <code>function*</code> keyword defines a generator function expression.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}</dt> - <dd>Pause and resume a generator function</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}</dt> - <dd>Delegate to another generator function or iterable object.</dd> - <dt>{{jsxref("Global_Objects/Array", "[]")}}</dt> - <dd>Array initializer/literal syntax.</dd> - <dt>{{jsxref("Operators/Object_initializer", "{}")}}</dt> - <dd>Object initializer/literal syntax.</dd> - <dt>{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}</dt> - <dd>Regular expression literal syntax.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> - <dd>Array comprehensions.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> - <dd>Generator comprehensions.</dd> - <dt>{{jsxref("Operators/Grouping", "( )")}}</dt> - <dd>Grouping operator.</dd> -</dl> - -<h3 id="Left-hand-side_expressions">Left-hand-side expressions</h3> - -<p>Left values are the destination of an assignment.</p> - -<dl> - <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> - <dd>Member operators provide access to a property or method of an object<br> - (<code>object.property</code> and <code>object["property"]</code>).</dd> - <dt>{{jsxref("Operators/new", "new")}}</dt> - <dd>The <code>new</code> operator creates an instance of a constructor.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/super", "super")}}</dt> - <dd>The <code>super</code> keyword calls the parent constructor.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}</dt> - <dd>The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.</dd> -</dl> - -<h3 id="Increment_and_decrement">Increment and decrement</h3> - -<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> - -<dl> - <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> - <dd>Postfix increment operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> - <dd>Postfix decrement operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> - <dd>Prefix increment operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> - <dd>Prefix decrement operator.</dd> -</dl> - -<h3 id="Unary_operators">Unary operators</h3> - -<p>A unary operation is operation with only one operand.</p> - -<dl> - <dt>{{jsxref("Operators/delete", "delete")}}</dt> - <dd>The <code>delete</code> operator deletes a property from an object.</dd> - <dt>{{jsxref("Operators/void", "void")}}</dt> - <dd>The <code>void</code> operator discards an expression's return value.</dd> - <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> - <dd>The <code>typeof</code> operator determines the type of a given object.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> - <dd>The unary plus operator converts its operand to Number type.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> - <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> - <dd>Bitwise NOT operator.</dd> - <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> - <dd>Logical NOT operator.</dd> -</dl> - -<h3 id="Arithmetic_operators">Arithmetic operators</h3> - -<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> - -<dl> - <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> - <dd>Addition operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> - <dd>Subtraction operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> - <dd>Division operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> - <dd>Multiplication operator.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> - <dd>Remainder operator.</dd> -</dl> - -<h3 id="Relational_operators">Relational operators</h3> - -<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> - -<dl> - <dt>{{jsxref("Operators/in", "in")}}</dt> - <dd>The <code>in</code> operator determines whether an object has a given property.</dd> - <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> - <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> - <dd>Less than operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> - <dd>Greater than operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> - <dd>Less than or equal operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> - <dd>Greater than or equal operator.</dd> -</dl> - -<h3 id="Equality_operators">Equality operators</h3> - -<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> - -<dl> - <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> - <dd>Equality operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> - <dd>Inequality operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> - <dd>Identity operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> - <dd>Nonidentity operator.</dd> -</dl> - -<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> - -<p>Operations to shift all bits of the operand.</p> - -<dl> - <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> - <dd>Bitwise left shift operator.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> - <dd>Bitwise right shift operator.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> - <dd>Bitwise unsigned right shift operator.</dd> -</dl> - -<h3 id="Binary_bitwise_operators">Binary bitwise operators</h3> - -<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> - -<dl> - <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> - <dd>Bitwise AND.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> - <dd>Bitwise OR.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> - <dd>Bitwise XOR.</dd> -</dl> - -<h3 id="Binary_logical_operators">Binary logical operators</h3> - -<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> - -<dl> - <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> - <dd>Logical AND.</dd> - <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> - <dd>Logical OR.</dd> -</dl> - -<h3 id="Conditional_ternary_operator">Conditional (ternary) operator</h3> - -<dl> - <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> - <dd> - <p>The conditional operator returns one of two values based on the logical value of the condition.</p> - </dd> -</dl> - -<h3 id="Assignment_operators">Assignment operators</h3> - -<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> - -<dl> - <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> - <dd>Assignment operator.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> - <dd>Multiplication assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> - <dd>Division assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> - <dd>Remainder assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> - <dd>Addition assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> - <dd>Subtraction assignment</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> - <dd>Left shift assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> - <dd>Right shift assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> - <dd>Unsigned right shift assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> - <dd>Bitwise AND assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> - <dd>Bitwise XOR assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> - <dd>Bitwise OR assignment.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> - {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> - <dd> - <p>Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.</p> - </dd> -</dl> - -<h3 id="Comma_operator">Comma operator</h3> - -<dl> - <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> - <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> -</dl> - -<h3 id="Non-standard_features">Non-standard features</h3> - -<dl> - <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> - <dd>The <code>function</code> keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.</dd> - <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> - <dd>The expression closure syntax is a shorthand for writing simple function.</dd> -</dl> - -<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>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>New: Spread operator, destructuring assignment, <code>super</code> keyword, Array comprehensions, Generator comprehensions</td> - </tr> - </tbody> -</table> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">Operator precedence</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/new/index.html b/files/it/web/javascript/reference/operators/new/index.html deleted file mode 100644 index 291917479e..0000000000 --- a/files/it/web/javascript/reference/operators/new/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: operatore new -slug: Web/JavaScript/Reference/Operators/new -tags: - - Espressioni di sinistra - - JavaScript - - Operatore -translation_of: Web/JavaScript/Reference/Operators/new ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>L'<strong>operatore <code><font face="Consolas, Liberation Mono, Courier, monospace">new</font></code></strong> crea un'istanza di un tipo di oggetto definito dall'utente o di uno dei tipi di oggetto nativi che ha una funzione costruttore.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">new <em>constructor</em>[([<em>arguments</em>])]</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>constructor</code></dt> - <dd>Una funzione che specifica il tipo dell'oggetto istanziato.</dd> -</dl> - -<dl> - <dt><code>arguments</code></dt> - <dd>Una lista di valori con i quali <code>constructor</code> sarà chiamato.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Creare un oggetto definito dall'utente richiede due step:</p> - -<ol> - <li>Definire il tipo di oggetto scrivendo una funzione.</li> - <li>Creare un'istanza dell'oggetto con <code>new</code>.</li> -</ol> - -<p>Per definire un tipo di oggetto, crea una funzione per il tipo di oggetto che specifichi il suo nome e le sue proprietà. Un oggetto può avere una proprietà che è se stessa un oggetto. Vedi l'esempio sotto.</p> - -<p>Quando il codice <code>new <em>Foo</em>(...)</code> viene eseguito, ecco cosa accade:</p> - -<ol> - <li>Un nuovo oggetto viene creato ed eredita da <code><em>Foo</em>.prototype</code>.</li> - <li>La funzione costruttore <em>Foo</em> viene chiamata con gli argomenti specificati e con <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> legato all'oggetto appena creato. <code>new Foo </code>è identica a <code>new Foo()</code>, ovvero se nessun argomento è specificato, <em>Foo</em> viene chiamato senza argumenti.</li> - <li>L'oggetto ritornato dalla funzione costruttore diventa il risultato dell'intera espressione <code>new</code>. Se la funzione costruttore non ritorna esplicitamente un oggetto, viene invece usato l'oggetto creato nello step 1. (Normalmente i costruttori non ritornano un valore, ma possono scegliere di farlo se vogliono sovrascrivere il processo di creazione di un normale oggetto).</li> -</ol> - -<p>Puoi sempre aggiungere una proprietà all'oggetto che hai creato precedentemente. Per esempio, la dichiarazione <code>car1.color = "black"</code> aggiunge una proprietà <code>color</code> a <code>car1</code>, e gli assegna il valore di "<code>black</code>". Tuttavia, questo non influenza nessun altro oggetto. Per aggiungere una nuova proprietà a tutti gli oggetti dello stesso tipo, devi aggiungere la proprietà alla definizione del tipo di oggetto, in questo caso <code>Car</code>.</p> - -<p>Puoi aggiungere una proprietà condivisa ad un tipo di oggetto che hai definito prima usando la proprietà <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">Function.prototype</a></code>.</p> - -<p>Questo definisce una proprietà che è condivisa da tutti gli oggetti creati con quella funzione, piuttosto che solo da un'istanza di quel tipo di oggetto. Il seguente codice aggiunge una proprietà con il valore <code>null</code> a tutti gli oggetti di tipo <code>car, </code>e poi sovrascrive quel valore con la stringa "<code>black</code>" solo nell'oggetto istanza <code>car1.</code> Per altre informazioni, vedi <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">prototype</a>.</p> - -<p> </p> - -<pre class="brush: js">function Car() {} -car1 = new Car(); -car2 = new Car(); - -console.log(car1.color); // undefined - -Car.prototype.color = "original color"; -console.log(car1.color); // original color - -car1.color = 'black'; -console.log(car1.color); // black - -console.log(car1.__proto__.color) //original color -console.log(car2.__proto__.color) //original color -console.log(car1.color) // black -console.log(car2.color) // original color -</pre> - -<p class="note">Se non hai usato l'operatore <code>new</code>, <strong>la funzione constructor verrà invocata come una qualunque altra funzione</strong>, <em>senza creare un nuovo Object.</em><strong> </strong>in questo caaso, anche il valore di <code>this</code> è diverso.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Tipo_di_oggetto_e_oggetto_istanza">Tipo di oggetto e oggetto istanza</h3> - -<p>Metti caso di volere creare un tipo di oggetto per le macchine. Vuoi che questo tipo di oggetto si chiami <code>car</code>, e vuoi che abbia queste proprietà: make (brand, marca), model (modello) e year (anno). Per fare questo, potresti scrivere la seguente funzione:</p> - -<pre class="brush: js">function Car(make, model, year) { - this.make = make; - this.model = model; - this.year = year; -} -</pre> - -<p>Adesso puoi creare un oggetto chiamato <code>myCar</code> in questo modo:</p> - -<pre class="brush: js">var mycar = new Car("Eagle", "Talon TSi", 1993); -</pre> - -<p>Questa dichiarazione crea <code>myCar </code>e gli assegna i valori specificati per le sue proprietà. Poi il valore di <code>mycar.make</code> è "Eagle", <code>mycar.year</code> è il numero intero 1993, e così via.</p> - -<p>Puoi creare quanti oggetti <code>Car</code> vuoi utilizzando <code>new</code>. Per esempio:</p> - -<pre class="brush: js">var kenscar = new Car("Nissan", "300ZX", 1992); -</pre> - -<h3 id="Proprietà_dell'oggetto_che_è_se_stesso_un_oggetto">Proprietà dell'oggetto che è se stesso un oggetto</h3> - -<p>Supponi di definire un oggetto <code>person</code> in questo modo:</p> - -<pre class="brush: js">function Person(name, age, sex) { - this.name = name; - this.age = age; - this.sex = sex; -} -</pre> - -<p>E poi istanzi due nuove oggetti <code>Person</code> in questo modo:</p> - -<pre class="brush: js">var rand = new Person("Rand McNally", 33, "M"); -var ken = new Person("Ken Jones", 39, "M"); -</pre> - -<p>Poi puoi riscrivere la definizione di <code>Car</code> per includere una proprietà <code>owner</code> (proprietario) che accetta un oggetto persona, ecco come:</p> - -<pre class="brush: js">function Car(make, model, year, owner) { - this.make = make; - this.model = model; - this.year = year; - this.owner = owner; -} -</pre> - -<p>Per istanziare i nuovi oggetti, poi fai così:</p> - -<pre class="brush: js">var car1 = new Car("Eagle", "Talon TSi", 1993, rand); -var car2 = new Car("Nissan", "300ZX", 1992, ken); -</pre> - -<p>Invece di passare una stringa letterale o un valore intero quando crei i nuovi oggetti, le dichiarazioni sopra passano gli oggetti <code>rand</code> e <code><font face="Consolas, Liberation Mono, Courier, monospace">ken</font></code> come parametri per i proprietari. Per cercare il nome del proprietario (owner) in <code><font face="Consolas, Liberation Mono, Courier, monospace">car2</font></code>, puoi accedere alla seguente proprietà:</p> - -<pre class="brush: js">car2.owner.name -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Status</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}</td> - <td>{{Spec2('ES3')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<p>{{Compat("javascript.operators.new")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Reflect.construct()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/operators/spread_syntax/index.html b/files/it/web/javascript/reference/operators/spread_syntax/index.html deleted file mode 100644 index 9c300f9257..0000000000 --- a/files/it/web/javascript/reference/operators/spread_syntax/index.html +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: Spread syntax -slug: Web/JavaScript/Reference/Operators/Spread_syntax -tags: - - ECMAScript 2015 - - Iterator - - JavaScript - - Referenza -translation_of: Web/JavaScript/Reference/Operators/Spread_syntax ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>La <strong>Spread syntax</strong> consente un iterabile come un'espressione di un array o una stringa da espandere in punti in cui sono previsti zero o più argomenti (per chiamate di funzione) o elementi (per letterali di array) o un'espressione di oggetto da espandere in posizioni dove zero o più sono previste coppie di valori (per valori letterali oggetto)..</p> - -<div>{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<p>Per chiamate di funzione:</p> - -<pre class="syntaxbox">myFunction(...iterableObj); -</pre> - -<p>Per letterali di un array o stringhe:</p> - -<pre class="syntaxbox">[...iterableObj, '4', 'five', 6];</pre> - -<p>Per gli oggetti letterali (novità in ECMAScript 2018):</p> - -<pre class="syntaxbox">let objClone = { ...obj };</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Spread_nelle_chiamate_delle_funzioni">Spread nelle chiamate delle funzioni</h3> - -<h4 id="Sostituire_apply()">Sostituire <code>apply()</code></h4> - -<p>È comune utilizzare {{jsxref("Function.prototype.apply()")}} nei casi in cui vuoi utilizzare gli elementi di un array come argomenti di una funzione.</p> - -<pre class="brush: js">function myFunction(x, y, z) { } -var args = [0, 1, 2]; -myFunction.apply(null, args);</pre> - -<p>Con la spread syntax può essere scritto come:</p> - -<pre class="brush: js">function myFunction(x, y, z) { } -var args = [0, 1, 2]; -myFunction(...args);</pre> - -<p>Qualsiasi argomento nell'elenco di argomenti può utilizzare la spread syntax e può essere utilizzato più volte.</p> - -<pre class="brush: js">function myFunction(v, w, x, y, z) { } -var args = [0, 1]; -myFunction(-1, ...args, 2, ...[3]);</pre> - -<h4 id="Apply_for_new">Apply for <code>new</code></h4> - -<p>When calling a constructor with {{jsxref("Operators/new", "new")}} it's not possible to <strong>directly</strong> use an array and <code>apply</code> (<code>apply</code> does a <code>[[Call]]</code> and not a <code>[[Construct]]</code>). However, an array can be easily used with <code>new</code> thanks to spread syntax:</p> - -<pre class="brush: js">var dateFields = [1970, 0, 1]; // 1 Jan 1970 -var d = new Date(...dateFields); -</pre> - -<p>To use new with an array of parameters without spread syntax, you would have to do it <strong>indirectly</strong> through partial application:</p> - -<pre class="brush: js">function applyAndNew(constructor, args) { - function partial () { - return constructor.apply(this, args); - }; - if (typeof constructor.prototype === "object") { - partial.prototype = Object.create(constructor.prototype); - } - return partial; -} - - -function myConstructor () { - console.log("arguments.length: " + arguments.length); - console.log(arguments); - this.prop1="val1"; - this.prop2="val2"; -}; - -var myArguments = ["hi", "how", "are", "you", "mr", null]; -var myConstructorWithArguments = applyAndNew(myConstructor, myArguments); - -console.log(new myConstructorWithArguments); -// (internal log of myConstructor): arguments.length: 6 -// (internal log of myConstructor): ["hi", "how", "are", "you", "mr", null] -// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}</pre> - -<h3 id="Spread_in_array_literals">Spread in array literals</h3> - -<h4 id="A_more_powerful_array_literal">A more powerful array literal</h4> - -<p>Without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}}, etc. With spread syntax this becomes much more succinct:</p> - -<pre class="brush: js">var parts = ['shoulders', 'knees']; -var lyrics = ['head', ...parts, 'and', 'toes']; -// ["head", "shoulders", "knees", "and", "toes"] -</pre> - -<p>Just like spread for argument lists, <code>...</code> can be used anywhere in the array literal and it can be used multiple times.</p> - -<h4 id="Copiare_un_array">Copiare un array</h4> - -<pre class="brush: js">var arr = [1, 2, 3]; -var arr2 = [...arr]; // like arr.slice() -arr2.push(4); - -// arr2 becomes [1, 2, 3, 4] -// arr remains unaffected -</pre> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> La spread syntax diventa effettivamente un livello profondo durante la copia di un array. Pertanto, potrebbe non essere adatto per copiare arrau multidimensionali come mostra il seguente esempio (è lo stesso con {{jsxref("Object.assign()")}} e spread syntax).</p> -</div> - -<pre class="brush: js">var a = [[1], [2], [3]]; -var b = [...a]; -b.shift().shift(); // 1 -// Adesso anche l'array a è influenzato: [[], [2], [3]] -</pre> - -<h4 id="Un_modo_migliore_per_concatenare_gli_array">Un modo migliore per concatenare gli array</h4> - -<p>{{jsxref("Array.prototype.concat()")}} è spesso usato per concatenare un array alla fine di un array esistente. Senza la spread syntax questo è fatto così:</p> - -<pre class="brush: js">var arr1 = [0, 1, 2]; -var arr2 = [3, 4, 5]; -// Append all items from arr2 onto arr1 -arr1 = arr1.concat(arr2);</pre> - -<p>Con la spread syntax questo diventa:</p> - -<pre class="brush: js">var arr1 = [0, 1, 2]; -var arr2 = [3, 4, 5]; -arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5] -</pre> - -<p>{{jsxref("Array.prototype.unshift()")}} è spesso usato per inserire un array di valori all'inizio di un array esistente. Senza la spread syntax questo è fatto così:</p> - -<pre class="brush: js">var arr1 = [0, 1, 2]; -var arr2 = [3, 4, 5]; -// Spostare all'inizio tutti gli elementi da arr2 a arr1 -Array.prototype.unshift.apply(arr1, arr2) // arr1 ora è [3, 4, 5, 0, 1, 2]</pre> - - - -<p>Con la spread syntax questo diventa:</p> - - - -<pre class="brush: js">var arr1 = [0, 1, 2]; -var arr2 = [3, 4, 5]; -arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2] -</pre> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: A differenza di <code>unshift()</code>, questo crea un nuovo <code>arr1</code>, e non modifica l'array originale <code>arr1</code>.</p> -</div> - -<h3 id="Spread_in_object_literals">Spread in object literals</h3> - -<p>The <a href="https://github.com/tc39/proposal-object-rest-spread">Rest/Spread Properties for ECMAScript</a> proposal (stage 4) adds spread properties to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object literals</a>. It copies own enumerable properties from a provided object onto a new object.</p> - -<p>Lo Shallow-cloning (escluso il prototipo) o fusione di oggetti è ora possibile usando una sintassi più breve di {{jsxref("Object.assign()")}}.</p> - -<pre class="brush: js">var obj1 = { foo: 'bar', x: 42 }; -var obj2 = { foo: 'baz', y: 13 }; - -var clonedObj = { ...obj1 }; -// Object { foo: "bar", x: 42 } - -var mergedObj = { ...obj1, ...obj2 }; -// Object { foo: "baz", x: 42, y: 13 }</pre> - -<p>Nota che {{jsxref("Object.assign()")}} attiva i <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setters</a> mentre la spread syntax non lo fa.</p> - -<p>Nota che non è possibile sostituire o imitare la funzione {{jsxref("Object.assign()")}}:</p> - -<pre class="brush: js">var obj1 = { foo: 'bar', x: 42 }; -var obj2 = { foo: 'baz', y: 13 }; -const merge = ( ...objects ) => ( { ...objects } ); - -var mergedObj = merge ( obj1, obj2); -// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } } - -var mergedObj = merge ( {}, obj1, obj2); -// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }</pre> - -<p>Nell'esempio precedente, la spread syntax non funziona come previsto: estende una serie di argomenti nel letterale dell'oggetto, a causa del parametro rest.</p> - -<h3 id="Solo_per_iterabili">Solo per iterabili</h3> - -<p>La spread syntax (diversa dal caso delle spread properties) può essere applicata solo agli oggetti <a href="/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">iterabili</a>:</p> - -<pre class="brush: js">var obj = {'key1': 'value1'}; -var array = [...obj]; // TypeError: obj non è iterabile -</pre> - -<h3 id="Diffusione_con_molti_valori">Diffusione con molti valori</h3> - -<p>Quando si utilizza la sintassi di diffusione per le chiamate di funzione, tenere presente la possibilità di superare il limite di lunghezza dell'argomento del motore JavaScript. Vedi {{jsxref("Function.prototype.apply", "apply()")}} per maggiori dettagli.</p> - -<h2 id="Rest_syntax_(parametri)">Rest syntax (parametri)</h2> - -<p>La Rest syntax sembra esattamente come la spread syntax, ma è usata per destrutturare array e oggetti. In un certo senso, la Rest syntax è l'opposto della spread syntax: spread 'espande' un array nei suoi elementi, mentre la rest syntax raccoglie più elementi e li 'condensa' in un singolo elemento. Vedi <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/rest_parameters">rest parameters.</a></p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ES2015', '#sec-array-initializer')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definito in diverse sezioni della specifica: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-array-initializer">Array Initializer</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-argument-lists">Argument Lists</a></td> - </tr> - <tr> - <td>{{SpecName('ES2018', '#sec-object-initializer')}}</td> - <td>{{Spec2('ES2018')}}</td> - <td>Definito in <a href="http://www.ecma-international.org/ecma-262/9.0/#sec-object-initializer">Object Initializer</a></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array-initializer')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>Nessun cambiamento.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object-initializer')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>Nessun cambiamento.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.operators.spread")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/rest_parameters">Rest parameters</a> (anche ‘<code>...</code>’)</li> - <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">fn.apply</a> (anche ‘<code>...</code>’)</li> -</ul> diff --git a/files/it/web/javascript/reference/operators/super/index.html b/files/it/web/javascript/reference/operators/super/index.html deleted file mode 100644 index aee5f694b1..0000000000 --- a/files/it/web/javascript/reference/operators/super/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: super -slug: Web/JavaScript/Reference/Operators/super -translation_of: Web/JavaScript/Reference/Operators/super ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>La parola chiave <strong>super</strong> viene usata per chiamare le funzioni dell'oggetto padre.</p> - -<p>Il <code>super.prop</code> ed espressioni con <code>super[expr]</code> sono valide in ogni <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">definizione di metodo</a> sia nelle <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classi</a> e <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">oggetti literals</a>.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">super([arguments]); // chiama il costruttore padre. -super.functionOnParent([arguments]); -</pre> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Quando viene usata in un costruttore, la parola chiave <code>super</code> deve essere usata prima della parola chiave <code>this</code>. La parola chiave <code>super</code> può essere usata anche per chiamare funzioni dell'oggetto padre.</p> - -<h2 id="Esempio">Esempio</h2> - -<h3 id="Usare_super_nelle_classi">Usare <code>super</code> nelle classi</h3> - -<p>Questo pezzo di codice è preso da <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>). <code>super</code> è chiamato per evitare la duplicazione del codice comune ad entrambi i costruttori <code>Rectangle</code> e <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Square</span></font>.</p> - -<pre class="brush: js">class Polygon { - constructor(height, width) { - this.name = 'Polygon'; - this.height = height; - this.width = width; - } - sayName() { - console.log('Hi, I am a ', this.name + '.'); - } -} - -class Square extends Polygon { - constructor(length) { - this.height; // ReferenceError, super deve essere chiamato per primo! - - // Chiama il costruttore della classe padre - super(length, length); - - // Nota: Nelle classi derivate super() deve essere chiamato prima - // dell'uso di 'this'. - this.name = 'Square'; - } - - get area() { - return this.height * this.width; - } - - set area(value) { - this.area = value; - } -}</pre> - -<h3 id="Usare_super_con_metodi_statici">Usare <code>super</code> con metodi statici</h3> - -<p>Puoi usare super anche chiamare metodi <a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">statici</a>.</p> - -<pre class="brush: js"><code>class Rectangle { - constructor() {} - static logNbSides() { - return 'I have 4 sides'; - } -} - -class Square extends Rectangle { - constructor() {} - static logDescription() { - return super.logNbSides() + ' which are all equal'; - } -} -Square.logDescription(); // 'I have 4 sides which are all equal'</code></pre> - -<h3 id="Cancellare_una_proprietà_del_super_causa_eccezione">Cancellare una proprietà del super causa eccezione</h3> - -<p>Non puoi cancellare una proprietà della classe padre usando l' <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">operatore delete</a> e <code>super.prop</code> o <code>super[esperssione]</code>, questo causerà un {{jsxref("ReferenceError")}}.</p> - -<pre class="brush: js">class Base { - constructor() {} - foo() {} -} -class Derived extends Base { - constructor() {} - delete() { - delete super.foo; - } -} - -new Derived().delete(); // ReferenceError: uso della delete con 'super'. </pre> - -<h3 id="Super.prop_non_può_sovrascrivere_proprietà_non_scrivibili"><code>Super.prop</code> non può sovrascrivere proprietà non scrivibili</h3> - -<p>Quando si definisce una proprietà non riscrivibile con ad esempio {{jsxref("Object.defineProperty")}}, <code>super</code> non può modificarne il valore.</p> - -<pre class="brush: js"><code>class X { - constructor() { - Object.defineProperty(this, 'prop', { - configurable: true, - writable: false, - value: 1 - }); - } -} - -class Y extends X { - constructor() { - super(); - } - foo() { - super.prop = 2; // Non posso sovrascrivere il valore. - } -} - -var y = new Y(); -y.foo(); // TypeError: "prop" is read-only -console.log(y.prop); // 1</code></pre> - -<h3 id="Uso_di_super.prop_in_oggetti_literals">Uso di <code>super.prop</code> in oggetti literals</h3> - -<p>Super può essere utilizzato anche nella <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">initializzazione di oggetti</a> con notazione letterale. In questo esempio, due oggetti definiscono un metodo. Nel secondo oggetto, <code>super</code> chiama il metodo del primo oggetto. Questo funziona grazie all'aiuto di {{jsxref("Object.setPrototypeOf()")}} con cui siamo in grado di impostare il prototipo di <code>obj2</code> con l'oggetto <code>obj1</code>, in modo che <code>super</code> sia in grado di trovare <code>method1</code> in <code>obj1</code>.</p> - -<pre class="brush: js">var obj1 = { - method1() { - console.log("method 1"); - } -} - -var obj2 = { - method2() { - super.method1(); - } -} - -Object.setPrototypeOf(obj2, obj1); -obj2.method2(); // logs "method 1" -</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('ES6', '#sec-super-keyword', 'super')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibili">Browser compatibili</h2> - -<p>{{Compat("javascript.operators.super")}}</p> - -<div id="compat-desktop"></div> - -<h2 id="Gecko_specific_notes">Gecko specific notes</h2> - -<ul> - <li><code>super()</code> non funziona come previsto in prototipi built-in.</li> -</ul> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classi</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/this/index.html b/files/it/web/javascript/reference/operators/this/index.html deleted file mode 100644 index cd324d2bcf..0000000000 --- a/files/it/web/javascript/reference/operators/this/index.html +++ /dev/null @@ -1,410 +0,0 @@ ---- -title: this -slug: Web/JavaScript/Reference/Operators/this -translation_of: Web/JavaScript/Reference/Operators/this ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>La <strong>keyword</strong> <strong>di</strong> <strong>funzione <code>this</code> </strong>si comporta in modo leggermente differente in JavaScript rispetto ad altri linguaggi. Esistono inoltre alcune differenze tra <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">strict mode</a> e non-strict mode.</p> - -<p>Nella maggior parte dei casi, il valore di <code>this</code> è determinato da come la funzione viene invocata (chiamata). Il valore di <code>this</code> non può essere impostato per assegnamento durante l'esecuzione, e potrebbe essere differente ogni volta in cui la funzione viene chiamata. ES5 ha introdotto il metodo <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a></code> per <a href="#The_bind_method">impostare il valore di <code>this</code> indipendentemente da come la funzione è invocata</a>. ECMAScript 2015 ha introdotto <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions/Arrow_functions">le funzione a freccia ( arrow function )</a>, in cui la keyword <code>this </code>viene lessicalmente incorporata nello <em>scope</em> corrente ( <code>lo scope </code>del contesto di esecuzione relativo al blocco corrente<code> ). </code></p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">this</pre> - -<h2 id="Contesto_Globale">Contesto Globale</h2> - -<p>Nel contesto di esecuzione globale (fuori da qualsiasi funzione), <code>this</code> si riferisce all'oggetto globale, sia che ci si trovi in strict mode, sia che ci si trovi in non-strict mode.</p> - -<pre class="brush:js">console.log(this.document === document); // true - -// In web browsers, the window object is also the global object: -console.log(this === window); // true - -this.a = 37; -console.log(window.a); // 37 -</pre> - -<h2 id="Contesto_di_funzione">Contesto di funzione</h2> - -<p>All'interno di una funzione, il valore di <code>this</code> dipende da come la funzione è invocata.</p> - -<h3 id="Chiamata_semplice">Chiamata semplice</h3> - -<pre class="brush:js">function f1(){ - return this; -} - -f1() === window; // global object -</pre> - -<p>In questo caso, il valore di <code>this</code> non viene impostato dalla chiamata. Visto che il codice non è in strict mode, il valore di <code>this</code> deve sempre essere un oggetto quindi viene impostato di default sull'oggetto globale.</p> - -<pre class="brush:js">function f2(){ - "use strict"; // see strict mode - return this; -} - -f2() === undefined; -</pre> - -<p>In strict mode, il valore di <code>this</code> rimane impostato sul valore definito al momento dell'ingresso nel contesto di esecuzione. Se non è definito, resta undefined. Può anche essere impostato a qualsiasi valore, come <code>null</code> o <code>42</code> o <code>"I am not this"</code>.</p> - -<div class="note"><strong>Nota:</strong> Nel secondo esempio, <code>this</code> dovrebbe essere <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a>, perchè <code>f2</code> viene invocata senza specificare alcuna base (per esempio, <code>window.f2()</code>). Alcuni browser non hanno implementato questo orientamento, quando hanno deciso di supportare lo <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="Strict mode">strict mode</a>. Come risultato, questi browser restituivano, in modo non corretto, l'oggetto <code>window</code>.</div> - -<h3 id="Funzioni_Arrow">Funzioni Arrow</h3> - -<p>Nelle <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">funzioni arrow</a>, <code>this</code> è assegnato lessicalmente, assume cioè il valore del contesto di esecuzione che contiene <code>this.</code> In codice globale punta all'oggetto globale:</p> - -<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> globalObject <span class="operator token">=</span> <span class="keyword token">this</span><span class="punctuation token">;</span> -<span class="keyword token">var</span> foo <span class="operator token">=</span> <span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="keyword token">this</span><span class="punctuation token">)</span><span class="punctuation token">;</span> -console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="function token">foo</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">===</span> globalObject<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true</span></code></pre> - -<p>Non importa come <code>foo</code> sia invocato, <code>this</code> punterà all'oggetto globale. Questo è ancora valido se è chiamato come metodo di un oggetto (che solitamente punterebbe il valore di <code>this</code> sullo stesso) tramite chiamate dei metodi <code>call</code> o <code>apply</code> o <code>bind</code></p> - -<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Call as a method of an object</span> -<span class="keyword token">var</span> obj <span class="operator token">=</span> <span class="punctuation token">{</span>foo<span class="punctuation token">:</span> foo<span class="punctuation token">}</span><span class="punctuation token">;</span> -console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>obj<span class="punctuation token">.</span><span class="function token">foo</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">===</span> globalObject<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true</span> - -<span class="comment token">// Attempt to set this using call</span> -console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>foo<span class="punctuation token">.</span><span class="function token">call</span><span class="punctuation token">(</span>obj<span class="punctuation token">)</span> <span class="operator token">===</span> globalObject<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true</span> - -<span class="comment token">// Attempt to set this using bind</span> -foo <span class="operator token">=</span> foo<span class="punctuation token">.</span><span class="function token">bind</span><span class="punctuation token">(</span>obj<span class="punctuation token">)</span><span class="punctuation token">;</span> -console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="function token">foo</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">===</span> globalObject<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true</span></code></pre> - -<p>in ogni caso il valore di this all'interno di foo è impostato al valore di quando è stato creato (nell'esempio di sopra, l'oggetto globale). Lo stesso si applica per funzioni arrow create all'interno di altre funzioni: il loro valore di this è impostato a quello del contesto di esecuzione esterno.</p> - -<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Create obj with a method bar that returns a function that</span> -<span class="comment token">// returns its this. The returned function is created as </span> -<span class="comment token">// an arrow function, so its this is permanently bound to the</span> -<span class="comment token">// this of its enclosing function. The value of bar can be set</span> -<span class="comment token">// in the call, which in turn sets the value of the </span> -<span class="comment token">// returned function.</span> -<span class="keyword token">var</span> obj <span class="operator token">=</span> <span class="punctuation token">{</span> bar <span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> - <span class="keyword token">var</span> x <span class="operator token">=</span> <span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="keyword token">this</span><span class="punctuation token">)</span><span class="punctuation token">;</span> - <span class="keyword token">return</span> x<span class="punctuation token">;</span> - <span class="punctuation token">}</span> - <span class="punctuation token">}</span><span class="punctuation token">;</span> - -<span class="comment token">// Call bar as a method of obj, setting its this to obj</span> -<span class="comment token">// Assign a reference to the returned function to fn</span> -<span class="keyword token">var</span> fn <span class="operator token">=</span> obj<span class="punctuation token">.</span><span class="function token">bar</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> - -<span class="comment token">// Call fn without setting this, would normally default</span> -<span class="comment token">// to the global object or undefined in strict mode</span> -console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="function token">fn</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">===</span> obj<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true</span></code></pre> - -<p>Nel codice sopra, la funzione (chiamiamola funzione anonima A) assegnata a obj.bar restituisce un altra funzione (chiamiamola funzione anonima B) che viene creata come funzione arrow. Il risultato, è che this della funzione B è impostata permanentemente al valore di this di obj.bar (funzione A) quando viene chiamata. quando la funzione restituita (B) viene chiamata, il relativo this sarà sempre impostato al valore di partenza. Nel codice di esempio il this della funzione B è impostato al valore this della funzione A che è obj, pertanto resta impostato ad obj anche quando viene chiamato in un modo che imposterebbe this come undefined od oggetto globale (o qualunque altro metodo, come nel precedente esempio, nel contesto di esecuzione globale).</p> - -<p>In the above, the function(call it anonymous function A) assigned to <code>obj.bar</code> returns another function(call it anonymous function B) that is created as an arrow function. As a result, function B's <code>this</code> is permanently set to the <code>this</code> of <code>obj.bar</code> (function A)when called. When the returned function(function B) is called, its <code>this</code> will always be what it was set to initially. In the above code example, function B's <code>this</code> is set to function A's <code>this</code> which is obj, so it remains set to <code>obj</code> even when called in a manner that would normally set its <code>this</code> to <code>undefined</code> or the global object (or any other method as in the previous example in the global execution context).</p> - -<h3 id="Come_metodo_di_un_oggetto">Come metodo di un oggetto</h3> - -<p>Quando una funzione viene invocata come metodo di un oggetto, il <code>this</code>, all'interno della funzione, viene impostato sull'oggetto di cui la funzione è metodo.</p> - -<p>Nell'esempio seguente, quando <code>o.f()</code> viene invocata, all'interno della funzione <code>this</code> è associato all'oggetto <code>o</code>.</p> - -<pre class="brush:js">var o = { - prop: 37, - f: function() { - return this.prop; - } -}; - -console.log(o.f()); // logs 37 -</pre> - -<p>Da notare che questo comportamento non è per nulla influenzato dal come e dal dove la funzione sia stata definita. Nell'esempio precedente, abbiamo definito la funzione inline, come membro <code>f</code>, nel corso della definizione di <code>o</code>. Tuttavia, avremmo potuto facilmente definire la funzione prima, per poi associarla a <code>o.f</code>. Il risultato sarebbe stato lo stesso:</p> - -<pre class="brush:js">var o = {prop: 37}; - -function independent() { - return this.prop; -} - -o.f = independent; - -console.log(o.f()); // logs 37 -</pre> - -<p>Questo dimostra che la cosa più importante è che la funzione venga invocata dal membro<code> f</code> di <code>o</code>.</p> - -<p>In modo analogo, l'associazione di <code>this</code> è influenzata solo dal membro più vicino. Nell'esempio seguente, quando invochiamo la funzione, la invochiamo come metodo <code>g</code> dell'oggetto <code>o.b</code>. Questa volta, durante l'esecuzione, <code>this</code>, all'interno della funzione, sarà associata ad <code>o.b</code>. Il fatto che l'oggetto sia, esso stesso, un membro di <code>o</code> non ha alcuna conseguenza; la sola cosa che conti è il riferimento più immediato.</p> - -<pre class="brush:js">o.b = {g: independent, prop: 42}; -console.log(o.b.g()); // logs 42 -</pre> - -<h4 id="this_nella_prototype_chain_dell'oggetto"><code>this</code> nella prototype chain dell'oggetto</h4> - -<p>La stessa notazione è valida per i metodi definiti altrove nella prototype chain dell'oggetto. Se il metodo è sulla prototype chain di un oggetto, <code>this</code> si riferisce all'oggetto su cui il metodo è stato chiamato, come se il metodo appartenesse all'oggetto.</p> - -<pre class="brush:js">var o = {f:function(){ return this.a + this.b; }}; -var p = Object.create(o); -p.a = 1; -p.b = 4; - -console.log(p.f()); // 5 -</pre> - -<p>in questo esempio, l'oggetto assegnato alla variabile <code>p</code> non ha definita una proprietà <code>f</code>, la eredita dal suo prototipo. Non ha importanza che il controllo per <code>f</code> trovi eventualmente un membro con quel nome in <code>o</code>; il controllo è cominciato con un riferimento a <code>p.f</code>, quindi this all'interno della funzione assume il valore dell'oggetto a cui <code>p</code> si riferisce. Cioè, dal momento che <code>f</code> è chiamata come metodo di <code>p</code>, la parola chiave <code>this</code> al suo interno si riferisce a <code>p</code>. Questa è una interessante caratteristica dell'ereditarietà dei prototipi di javascript.</p> - -<h4 id="this_all'interno_di_metodi_getter_o_setter"><code>this</code> all'interno di metodi getter o setter</h4> - -<p>Ancora, la stessa notazione è valida quando una funzione è invocata all'interno di metodi get o set. In una funzione usata come getter o setter <code>this</code> viene collegata all'oggetto dal quale la proprietà è settata o ricavata.</p> - -<pre class="brush:js">function modulus(){ - return Math.sqrt(this.re * this.re + this.im * this.im); -} - -var o = { - re: 1, - im: -1, - get phase(){ - return Math.atan2(this.im, this.re); - } -}; - -Object.defineProperty(o, 'modulus', { - get: modulus, enumerable:true, configurable:true}); - -console.log(o.phase, o.modulus); // logs -0.78 1.4142 -</pre> - -<h3 id="Come_costruttore">Come costruttore</h3> - -<p>Quando una funzione è usata come un costruttore (tramite la parola chiave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code>), <code>this</code> è collegata al nuovo oggetto che viene costruito.</p> - -<p>Nota: mentre di default un costruttore restituisce l'oggetto riferenziato da <code>this</code>, può invece restituire qualche altro oggetto (se il valore di ritorno non è un oggetto, allora viene restituito l'oggetto <code>this</code>).</p> - -<pre class="brush:js">/* - * Constructors work like this: - * - * function MyConstructor(){ - * // Actual function body code goes here. - * // Create properties on |this| as - * // desired by assigning to them. E.g., - * this.fum = "nom"; - * // et cetera... - * - * // If the function has a return statement that - * // returns an object, that object will be the - * // result of the |new| expression. Otherwise, - * // the result of the expression is the object - * // currently bound to |this| - * // (i.e., the common case most usually seen). - * } - */ - -function C(){ - this.a = 37; -} - -var o = new C(); -console.log(o.a); // logs 37 - - -function C2(){ - this.a = 37; - return {a:38}; -} - -o = new C2(); -console.log(o.a); // logs 38 -</pre> - -<p>Nell'ultimo esempio <code>(C2)</code>, dal momento che è stato restituito un oggetto durante la costruzione, il nuovo oggetto a cui <code>this</code> era collegato viene semplicemente scartato. (Questo rende essenzialmente l'assegnazione "<code>this.a = 37;</code>" codice inutile. Non lo è in senso stretto, in quanto viene eseguito, ma può essere eliminato senza conseguenze).</p> - -<h3 id="I_metodi_call_e_apply">I metodi <code>call</code> e <code>apply</code></h3> - -<p>Dove una funzione usa la parola chiave <code>this</code>, il suo valore può essere collegato ad un qualsivoglia oggetto nella chiamata usando i metodi <code><a href="/it/docs/">call</a></code> o <code><a href="/it/docs/">apply</a></code><a href="/it/docs/"> </a>che tutte le funzioni ereditano da <code>Function.prototype</code>.<a href="/it/docs/"> </a></p> - -<pre class="brush:js">function add(c, d){ - return this.a + this.b + c + d; -} - -var o = {a:1, b:3}; - -// The first parameter is the object to use as -// 'this', subsequent parameters are passed as -// arguments in the function call -add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 - -// The first parameter is the object to use as -// 'this', the second is an array whose -// members are used as the arguments in the function call -add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 -</pre> - -<p>Notare che con <code>call</code> e <code>apply</code>, se il valore passato tramite <code>this</code> non è un oggetto, viene eseguito un tentativo di convertire tale valore in oggetto usando l'operazione interna <code>ToObject</code>. pertanto, se il valore passato è un primitivo come 7 o 'foo', questo verrà convertito ad <code>Object</code> usando il relativo costruttore, quindi il valore primitivo <code>7</code> viene convertito come <code>new</code> <code>Number(7)</code> e la stringa <code>'foo'</code> viene convertita come <code>new String('foo')</code>, per esempio:</p> - -<pre class="brush:js">function bar() { - console.log(Object.prototype.toString.call(this)); -} - -bar.call(7); // [object Number] -</pre> - -<h3 id="Il_metodo_bind">Il metodo <code>bind</code></h3> - -<p>ECMAScript 5 ha introdotto <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind</a></code>. Chiamare <code>f.bind(someObject)</code> crea una nuova funzione con lo stesso corpo e visibità di <code>f,</code> ma nella funzione originale si trova la parola chiave <code>this</code>, nella nuova funzione viene permanentemente collegato al primo argomento passato alla chiamata del metodo <code>bind</code>, ignorando come la funzione stessa venga usata. </p> - -<pre class="brush:js">function f(){ - return this.a; -} - -var g = f.bind({a:"azerty"}); -console.log(g()); // azerty - -var o = {a:37, f:f, g:g}; -console.log(o.f(), o.g()); // 37, azerty -</pre> - -<h3 id="Come_handler_degli_eventi_del_DOM">Come handler degli eventi del DOM</h3> - -<p>Quando una funzione viene usata come handler di eventi, i suoi riferimenti <code>this</code> sono puntati all'elemento che ha originato l'evento (alcuni Browser non seguono queste convenzioni per i listeners agguinti dinamicamente tramite metodi diversi da <code>addEventListener</code>).</p> - -<pre class="brush:js">// When called as a listener, turns the related element blue -function bluify(e){ - // Always true - console.log(this === e.currentTarget); - // true when currentTarget and target are the same object - console.log(this === e.target); - this.style.backgroundColor = '#A5D9F3'; -} - -// Get a list of every element in the document -var elements = document.getElementsByTagName('*'); - -// Add bluify as a click listener so when the -// element is clicked on, it turns blue -for(var i=0 ; i<elements.length ; i++){ - elements[i].addEventListener('click', bluify, false); -}</pre> - -<h3 id="In_un_handler_di_eventi_in-line">In un handler di eventi "in-line"</h3> - -<p>quando il codice è chiamato da un handler in-line, <code>this</code> punta all'elemento DOM sul quale il listener è posizionato:</p> - -<p>When code is called from an in–line handler, its <code>this</code> is set to the DOM element on which the listener is placed:</p> - -<pre class="brush:js"><button onclick="alert(this.tagName.toLowerCase());"> - Show this -</button> -</pre> - -<p>Sopra, <code>alert</code> mostra '<code>button</code>'. Notare comunque che this assume tale valore solo al di fuori di una funzione:</p> - -<p> </p> - -<pre class="brush:js"><button onclick="alert((function(){return this}()));"> - Show inner this -</button> -</pre> - -<p> </p> - -<p>in questo caso, nella funzione interna, <code>this</code> non punta all'elemento DOM quindi restituisce l'oggetto globale/window (cioè l'oggetto di default in modalità non-strict, in cui <code>this</code> non viene impostato dalla chiamata)</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}</td> - <td>{{Spec2('ES3')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - </tbody> -</table> - -<p> </p> - -<h2 id="Compatibilità_dei_browser">Compatibilità dei browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p> </p> - -<h2 id="Vedere_Anche">Vedere Anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">Strict mode</a></li> - <li><a href="http://bjorn.tipling.com/all-this">All this</a>, un articolo su <code>this</code> in diversi contesti (Inglese)</li> - <li><a href="http://rainsoft.io/gentle-explanation-of-this-in-javascript/">Semplice spiegazione della parola chiave 'this' in JavaScript (inglese)</a></li> -</ul> diff --git a/files/it/web/javascript/reference/operators/yield/index.html b/files/it/web/javascript/reference/operators/yield/index.html deleted file mode 100644 index cd7fe6adfa..0000000000 --- a/files/it/web/javascript/reference/operators/yield/index.html +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: yield -slug: Web/JavaScript/Reference/Operators/yield -translation_of: Web/JavaScript/Reference/Operators/yield ---- -<div>{{jsSidebar("Operators")}}</div> - -<p>La parola chiave <em>yield </em>è usata per mettere in pausa e far ripartire un generatore di funzione ({{jsxref("Statements/function*", "function*")}} or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/Legacy_generator_function">legacy generator function</a>).</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">[<em>rv</em>] = <strong>yield</strong> [<em>expression</em>];</pre> - -<dl> - <dt><code>espressione</code></dt> - <dd>Definisce il valore da ritornare dalla funzione generatore attraverso <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">the iterator protocol</a>. Se omesso, <code>undefined</code> viene restituito.</dd> - <dt><code>rv</code></dt> - <dd>Permette che il generatore catturi il valore dell'espressione per usarlo al prossimo avvio dell'esecuzione.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>The <code>yield</code> keyword causes generator function execution to pause and the value of the expression following the <code>yield</code> keyword is returned to the generator's caller. It can be thought of as a generator-based version of the <code>return</code> keyword.</p> - -<p>The <code>yield</code> keyword actually returns an <code>IteratorResult</code> object with two properties, <code>value</code> and <code>done</code>. The <code>value</code> property is the result of evaluating the <code>yield</code> expression, and <code>done</code> is a Boolean indicating whether or not the generator function has fully completed.</p> - -<p>Once paused on a <code>yield</code> expression, the generator's code execution remains paused until the generator's <code>next()</code> method is called. Each time the generator's <code>next()</code> method is called, the generator resumes execution and runs until it reaches one of the following:</p> - -<ul> - <li> A <code>yield</code>, which causes the generator to once again pause and return the generator's new value. The next time <code>next()</code> is called, execution resumes with the statement immediately after the <code>yield</code>.</li> - <li>{{jsxref("Statements/throw", "throw")}} is used to throw an exception from the generator. This halts execution of the generator entirely, and execution resumes in the caller as is normally the case when an exception is thrown.</li> - <li>The end of the generator function is reached; in this case, execution of the generator ends and an <code>IteratorResult</code> is returned to the caller in which the <code>value</code> is {{jsxref("undefined")}} and <code>done</code> is <code>true</code>.</li> - <li>A {{jsxref("Statements/return", "return")}} statement is reached. In this case, execution of the generator ends and an <code>IteratorResult</code> is returned to the caller in which the <code>value</code> is the value specified by the <code>return</code> statement and <code>done</code> is <code>true</code>.</li> -</ul> - -<p>If an optional value is passed to the generator's <code>next()</code> method, that value becomes the value returned by the generator's next <code>yield</code> operation.</p> - -<p>Between the generator's code path, its <code>yield</code> operators, and the ability to specify a new starting value by passing it to {{jsxref("Generator.prototype.next()")}}, generators offer enormous power and control.</p> - -<h2 id="Examples">Examples</h2> - -<p>The following code is the declaration of an example generator function, along with a helper function.</p> - -<pre class="brush: js">function* foo(){ - var index = 0; - while (index <= 2) // when index reaches 3, - // yield's done will be true - // and its value will be undefined; - yield index++; -}</pre> - -<p>Once a generator function is defined, it can be used by constructing an iterator as shown.</p> - -<pre class="brush: js">var iterator = foo(); -console.log(iterator.next()); // { value: 0, done: false } -console.log(iterator.next()); // { value: 1, done: false } -console.log(iterator.next()); // { value: 2, done: false } -console.log(iterator.next()); // { value: undefined, done: true }</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ES2015', '#', 'Yield')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</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>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>39</td> - <td>{{CompatGeckoDesktop("26.0")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>IteratorResult</code> object instead of throwing</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoDesktop("29.0")}}</td> - <td>{{CompatUnknown}}</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>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("26.0")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{ CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>IteratorResult</code> object instead of throwing</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("29.0")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> - -<ul> - <li>Starting with Gecko 29 {{geckoRelease(29)}}, the completed generator function no longer throws a {{jsxref("TypeError")}} "generator has already finished". Instead, it returns an <code>IteratorResult</code> object like <code>{ value: undefined, done: true }</code> ({{bug(958951)}}).</li> - <li>Starting with Gecko 33 {{geckoRelease(33)}}, the parsing of the <code>yield</code> expression has been updated to conform with the latest ES2015 specification ({{bug(981599)}}): - <ul> - <li>The expression after the <code>yield</code> keyword is optional and omitting it no longer throws a {{jsxref("SyntaxError")}}: <code>function* foo() { yield; }</code></li> - </ul> - </li> -</ul> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> - <li>{{jsxref("Statements/function*", "function*")}}</li> - <li>{{jsxref("Operators/function*", "function* expression")}}</li> - <li>{{jsxref("Operators/yield*", "yield*")}}</li> -</ul> |