From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../reference/operators/comma_operator/index.html | 106 ----- .../operators/conditional_operator/index.html | 172 -------- .../operators/destructuring_assignment/index.html | 451 --------------------- .../javascript/reference/operators/in/index.html | 198 --------- .../web/javascript/reference/operators/index.html | 282 ------------- .../javascript/reference/operators/new/index.html | 186 --------- .../reference/operators/spread_syntax/index.html | 257 ------------ .../reference/operators/super/index.html | 181 --------- .../javascript/reference/operators/this/index.html | 410 ------------------- .../reference/operators/yield/index.html | 163 -------- 10 files changed, 2406 deletions(-) delete mode 100644 files/it/web/javascript/reference/operators/comma_operator/index.html delete mode 100644 files/it/web/javascript/reference/operators/conditional_operator/index.html delete mode 100644 files/it/web/javascript/reference/operators/destructuring_assignment/index.html delete mode 100644 files/it/web/javascript/reference/operators/in/index.html delete mode 100644 files/it/web/javascript/reference/operators/index.html delete mode 100644 files/it/web/javascript/reference/operators/new/index.html delete mode 100644 files/it/web/javascript/reference/operators/spread_syntax/index.html delete mode 100644 files/it/web/javascript/reference/operators/super/index.html delete mode 100644 files/it/web/javascript/reference/operators/this/index.html delete mode 100644 files/it/web/javascript/reference/operators/yield/index.html (limited to 'files/it/web/javascript/reference/operators') 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 ---- -
{{jsSidebar("Operators")}}
- -

L'operatore virgola valuta ciascuno dei suoi operandi, da sinistra a destra, e restituisce il valore dell'ultimo operando.

- -
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
- - - -

Sintassi

- -
expr1, expr2, expr3...
- -

Parametri

- -
-
expr1, expr2, expr3...
-
Qualsiasi espressione.
-
- -

Descrizione

- -

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

- -

L'operatore virgola è completamente differente dalla virgola utilizzata negli array, negli oggetti, e negli argomenti e parametri di funzione.

- -

Esempi

- -

Considerando a un array di 2 dimensioni contenente 10 elementi per ciascun lato, il seguente codice utilizza l'operatore virgola per incrementare i e decrementare j contemporaneamente.

- -

Il seguente codice stampa i valori degli elementi in posizione diagonale dell'array:

- -
for (var i = 0, j = 9; i <= 9; i++, j--)
-  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
- -

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, a é impostato al valore di b = 3 (che é 3), ma l'espressione c = 4 continua a essere valutata e il suo valore viene restituito alla console (cioé 4). Questo é dovuto alla precedenza e all'associtività dell'operatore.

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

Elaborazione e restituzione

- -

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:

- -
function myFunc() {
-  var x = 0;
-
-  return (x += 1, x); // stesso comportamento di ++x;
-}
- -

Specificazioni

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-comma-operator', 'Comma operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.14', 'Comma operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES1', '#sec-11.14', 'Comma operator')}}{{Spec2('ES1')}}Initial definition
- -

Compatibilità con i browser

- - - -

{{Compat("javascript.operators.comma")}}

- -

Vedi anche

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

L'operatore condizionale (ternary) è  l'unico operatore JavaScript che necessità di tre operandi. Questo operatore è frequentemente usato al posto del comando if per la sua sintassi concisa e perché fornisce direttamente un espressione valutabile.

- -

Sintassi

- -
condizione ? espressione1 : espressione2 
- -

Parametri

- -
-
condizione
-
Un espressione booleana (che viene valutata in vero o falso).
-
- -
-
espressione1, espressione2
-
Espressione di qualunque tipo (vedi avanti nella pagina).
-
- -

Descrizione

- -

Se la condizione è vera, l'operatore ritorna il valore di espressione1; altrimenti, ritorna il valore di espressione2.  Per esempio, puoi usare questa espressione per mostrare un messaggio che cambia in base al valore della variabile isMember:

- -
"The fee is " + (isMember ? "$2.00" : "$10.00")
-
- -

Puoi anche assegnare variabili dipendenti dal risultato di un operatore ternario:

- -
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
- -

Sono anche possibili espressioni con operatori ternari multipli (nota: l'operatore condizionale è associativo a destra):

- -
var firstCheck = false,
-    secondCheck = false,
-    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
-
-console.log( access ); // logs "Access granted"
- -

Puoi anche usare l'operatore ternario direttamente senza assegnamenti e senza combinazioni con altre espressioni, con lo scopo di valutare operazioni alternative:

- -
var stop = false, age = 16;
-
-age > 18 ? location.assign("continue.html") : stop = true;
-
- -

Puoi anche valutare operazioni multiple separandole con delle virgole:

- -
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!")
-);
-
- -

Puoi anche valutare più operazioni durante l'assegnamento di una variabile. In questo caso, l'ultimo valore separato da una virgola nelle parentesi sarà il valore assegnato.

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

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Compatibilità con Browser

- -

{{CompatibilityTable}}

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

Vedi anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

La sintassi di assegnamento di destrutturazione è un'espressione JavaScript che rende possibile estrarre informazioni da array o oggetti in variabili distinte.

- -

Sintassi

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

Descrizione

- -

Le espressioni lettali degli oggetti e degli array forniscono un modo facile per creare ad hoc pacchetti di data.

- -
var x = [1, 2, 3, 4, 5];
- -

L'assegnamento di destrutturazione utilizza una sintassi simile, ma a sinistra dell'assegnamento sono definiti quali elementi estrarre dalla variabile sorgente (array o oggetti).

- -
var x = [1, 2, 3, 4, 5];
-var [y, z] = x;
-console.log(y); // 1
-console.log(z); // 2
-
- -

Questa capacità è simile alle caratteristiche presenti in linguaggi come Perl e Python.

- -

Destrutturazione di array

- -

Assegnamento semplice di variabile

- -
var foo = ["one", "two", "three"];
-
-var [one, two, three] = foo;
-console.log(one); // "one"
-console.log(two); // "two"
-console.log(three); // "three"
-
- -

Assegnamento separato dalla dichiarazione

- -

Il valore di una variabile può essere assegnato (sempre con la destrutturazione) in modo separato dalla dichiarazione della variabile stessa.

- -
var a, b;
-
-[a, b] = [1, 2];
-console.log(a); // 1
-console.log(b); // 2
-
- -

Valori default

- -

Ad una variabile può essere assegnato un valore default nel caso in cui il valore estratto dall'array sia undefined.

- -
var a, b;
-
-[a=5, b=7] = [1];
-console.log(a); // 1
-console.log(b); // 7
-
- -

Scambio di variabili

- -

Due valori di variabili possono essere scambiati in un assegnamento di destrutturazione.

- -

Senza l'assegnamento di destrutturazione, scambiare due valori richiede una variabile momentanea (o, in alcuni linguaggi low-level, il XOR-swap trick).

- -
var a = 1;
-var b = 3;
-
-[a, b] = [b, a];
-console.log(a); // 3
-console.log(b); // 1
-
- -

Fare il parsing di un array ritornato da una funzione

- -

È sempre stato possibile ritornare un array da una funzione. La destrutturazione può rendere più conciso lavorare con il valore di ritorno di un array

- -

In questo esempio, f() ritorna i valori [1, 2] come output, e questi possono essere analizzati in una singola linea con la destrutturazione.

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

Ignorare alcuni valori ritornati

- -

Puoi ignorare i valori ritornati nei quali non sei interessato:

- -
function f() {
-  return [1, 2, 3];
-}
-
-var [a, , b] = f();
-console.log(a); // 1
-console.log(b); // 3
-
- -

Puoi anche ignorare tutti i valori ritornati:

- -
[,,] = f();
-
- -

Assegnare il resto di un array ad una variabile

- -

Quando si destruttura un array, puoi assegnare la sua parte rimanente ad una variabile usando l'operatore rest (i 3 puntini):

- -
var [a, ...b] = [1, 2, 3];
-console.log(a); // 1
-console.log(b); // [2, 3]
- -

Estrarre valori da un match con un'espressione regolare

- -

Quando il metodo exec() 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.

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

Destrutturazione degli oggetti

- -

Assegnamento base

- -
var o = {p: 42, q: true};
-var {p, q} = o;
-
-console.log(p); // 42
-console.log(q); // true
-
- -

Assegnamento senza dichiarazione

- -

Il valore di una variabile può essere assegnato senza destrutturazione separatamente dalla sua dichiarazione.

- -
var a, b;
-
-({a, b} = {a:1, b:2});
- -
-

Le ( ) attorno l'assegnamento di destrutturazione sono obbligatorie quando si usa la destrutturazione degli oggetti letterali senza una dichiarazione.

- -

{a, b} = {a:1, b:2} non è sintassi valida, dato che {a, b} sulla sinistra è considerato un blocco e non un oggetto letterale.

- -

Tuttavia, ({a, b} = {a:1, b:2}) è valida, dato che var {a, b} = {a:1, b:2}

-
- -

Assegnamento a nuovi nomi di variabili 

- -

Una variabile può essere estratta da un oggetto e assegnata ad una variabile con un nome diverso da quello della proprietà dell'oggetto.

- -
var o = {p: 42, q: true};
-var {p: foo, q: bar} = o;
-
-console.log(foo); // 42
-console.log(bar); // true  
- -

Valori default

- -

Ad una variabile può essere assegnato un valore default nel caso in cui il valore estratto dall'oggetto sia undefined.

- -
var {a=10, b=5} = {a: 3};
-
-console.log(a); // 3
-console.log(b); // 5
- -

Impostare i valore default dei parametri di una funzione

- -

Versione ES5

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

Versione ES2015

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

Oggetti annidati e destrutturazione array

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

Iterazione con for...of e destrutturazione

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

Estrarre campi dagli oggetti passati come parametri delle funzioni

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

Questo estrae  id, displayNamefirstName da l'oggetto user e li stampa.

- -

Proprietà calcolate degli oggetti e destrutturazione

- -

I nomi delle proprietà calcolate degli oggetti, come sugli object literals, possono anche essere usate con la destrutturazione.

- -
let key = "z";
-let { [key]: foo } = { z: "bar" };
-
-console.log(foo); // "bar"
-
- -

Specificazioni

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ESDraft')}} 
- -

Compatibilità browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaratteristicaChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Supporto base{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("1.8.1") }}14{{CompatNo}}{{CompatNo}}7.1
Nomi delle proprietà calcolate{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("34") }}14{{CompatNo}}{{CompatNo}}{{CompatNo}}
Operatore spread{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("34") }}12[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaratteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Supporto base{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("1.0") }}{{CompatNo}}{{CompatNo}}8{{CompatChrome(49.0)}}
Nomi delle proprietà calcolate{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(49.0)}}
Operatore spread{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("34") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
-
- -

[1] Richiede "Attiva le caratteristiche sperimentali di JavaScript" per essere abilitato sotto `about:flags`

- -

Note specifiche a Firefox

- - - -

Vedi anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

L' operatore in dà come ritorno true se la proprietà specificata si trova nell'oggetto preso in considerazione.

- -

Restituisce false se la proprietà è stata eliminata tramite delete ma non nel caso in cui sia stata inizializzata undefined dal programmatore.

- -

Sintassi

- -
prop in nomeOggetto
- -

Parametri

- -
-
prop
-
Una stringa o simbolo che rappresenta il nome di una proprietà o indice di un array (i non-simboli verranno automaticamente convertiti in stringhe).
-
- -
-
nomeOggetto
-
Nome di un oggetto.
-
- -

Descrizione

- -

I seguenti esempi mostrano alcuni usi dell'operatore in.

- -
// 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 alberi
-"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
-
- -

Devi specificare un oggetto sul lato destro dell'operatore in. Per esempio, puoi specificare una stringa creata con il costruttore String, ma non puoi specificare una stringa literal.

- -
var colore1 = new String("verde");
-"length" in colore1 // ritorna true
-
-var color2 = "coral";
-// genera un errore (colore2 non è un oggetto String)
-"length" in colore2
-
- -

Usare l'operatore in con le proprietà deleted o undefined

- -

Se elimini una proprietà con l'operatore delete, l'operatore in ritorna false per quella proprietà.

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

Se setti una proprietà ad {{jsxref("Global_Objects/undefined", "undefined")}} ma non la cancelli, l'operatore in darà come ritorno true per quella proprietà.

- -
var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998};
-miaAuto.marca = undefined;  //inizializzo manualmente la proprietà 'marca' 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à
- -

 

- -

 

- -

 

- -
var alberi = new Array("sequoia", "lauro", "cedro", "quercia", "acero");
-alberi[3] = undefined;
-3 in alberi; // ritorna true
-
- -

Proprietà ereditate

- -

L'operatore in ritorna true per proprietà ereditate tramite prototipi.

- -
"toString" in {}; // returns true
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in JavaScript 1.4.
- -

Compatibilità con i browser

- -

{{CompatibilityTable}}

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

Vedi anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

Questo capitolo documenta tutti gli operatori, espressioni e parole chiave del linguaggio JavaScript.

- -

Espressioni e operatori per categoria

- -

Per la lista alfabetica consultare la sidebar di sinistra

- -

Espressioni Primarie

- -

Basic keywords and general expressions in JavaScript.

- -
-
{{jsxref("Operators/this", "this")}}
-
The this keyword refers to the function's execution context.
-
{{jsxref("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
-
Pause and resume a generator function
-
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{jsxref("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
{{jsxref("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Left-hand-side expressions

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}
-
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.
-
- -

Increment and decrement

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Unary operators

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

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.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Non-standard features

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function 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.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
- -

See also

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

L'operatore new crea un'istanza di un tipo di oggetto definito dall'utente o di uno dei tipi di oggetto nativi che ha una funzione costruttore.

- -

Sintassi

- -
new constructor[([arguments])]
- -

Parametri

- -
-
constructor
-
Una funzione che specifica il tipo dell'oggetto istanziato.
-
- -
-
arguments
-
Una lista di valori con i quali constructor sarà chiamato.
-
- -

Descrizione

- -

Creare un oggetto definito dall'utente richiede due step:

- -
    -
  1. Definire il tipo di oggetto scrivendo una funzione.
  2. -
  3. Creare un'istanza dell'oggetto con new.
  4. -
- -

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.

- -

Quando il codice new Foo(...) viene eseguito, ecco cosa accade:

- -
    -
  1. Un nuovo oggetto viene creato ed eredita da Foo.prototype.
  2. -
  3. La funzione costruttore Foo viene chiamata con gli argomenti specificati e con this legato all'oggetto appena creato. new Foo è identica a new Foo(), ovvero se nessun argomento è specificato, Foo viene chiamato senza argumenti.
  4. -
  5. L'oggetto ritornato dalla funzione costruttore diventa il risultato dell'intera espressione new. 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).
  6. -
- -

Puoi sempre aggiungere una proprietà all'oggetto che hai creato precedentemente. Per esempio, la dichiarazione car1.color = "black" aggiunge una proprietà  color a car1, e gli assegna il valore di "black". 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 Car.

- -

Puoi aggiungere una proprietà condivisa ad un tipo di oggetto che hai definito prima usando la proprietà Function.prototype.

- -

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 null a tutti gli oggetti di tipo car, e poi sovrascrive quel valore con la stringa "black" solo nell'oggetto istanza car1. Per altre informazioni, vedi prototype.

- -

 

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

Se non hai usato l'operatore newla funzione constructor verrà invocata come una qualunque altra funzionesenza creare un nuovo Object. in questo caaso, anche il valore di this è diverso.

- -

Esempi

- -

Tipo di oggetto e oggetto istanza

- -

Metti caso di volere creare un tipo di oggetto per le macchine. Vuoi che questo tipo di oggetto si chiami car, e vuoi che abbia queste proprietà: make (brand, marca), model (modello) e year (anno). Per fare questo, potresti scrivere la seguente funzione:

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
-
- -

Adesso puoi creare un oggetto chiamato myCar in questo modo:

- -
var mycar = new Car("Eagle", "Talon TSi", 1993);
-
- -

Questa dichiarazione crea myCar e gli assegna i valori specificati per le sue proprietà. Poi il valore di mycar.make è "Eagle", mycar.year è il numero intero 1993, e così via.

- -

Puoi creare quanti oggetti Car vuoi utilizzando new. Per esempio:

- -
var kenscar = new Car("Nissan", "300ZX", 1992);
-
- -

Proprietà dell'oggetto che è se stesso un oggetto

- -

Supponi di definire un oggetto person in questo modo:

- -
function Person(name, age, sex) {
-  this.name = name;
-  this.age = age;
-  this.sex = sex;
-}
-
- -

E poi istanzi due nuove oggetti Person in questo modo:

- -
var rand = new Person("Rand McNally", 33, "M");
-var ken = new Person("Ken Jones", 39, "M");
-
- -

Poi puoi riscrivere la definizione di Car per includere una proprietà owner (proprietario) che accetta un oggetto persona, ecco come:

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-}
-
- -

Per istanziare i nuovi oggetti, poi fai così:

- -
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
-var car2 = new Car("Nissan", "300ZX", 1992, ken);
-
- -

Invece di passare una stringa letterale o un valore intero quando crei i nuovi oggetti, le dichiarazioni sopra passano gli oggetti rand e ken come parametri per i proprietari. Per cercare il nome del proprietario (owner) in car2, puoi accedere alla seguente proprietà:

- -
car2.owner.name
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificheStatusCommento
{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Compatibilità browser

- -

{{Compat("javascript.operators.new")}}

- -

Vedi anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

La Spread syntax 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)..

- -
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
- - - -

Sintassi

- -

Per chiamate di funzione:

- -
myFunction(...iterableObj);
-
- -

Per letterali di un array o stringhe:

- -
[...iterableObj, '4', 'five', 6];
- -

Per gli oggetti letterali (novità in ECMAScript 2018):

- -
let objClone = { ...obj };
- -

Esempi

- -

Spread nelle chiamate delle funzioni

- -

Sostituire apply()

- -

È comune utilizzare {{jsxref("Function.prototype.apply()")}} nei casi in cui vuoi utilizzare gli elementi di un array come argomenti di una funzione.

- -
function myFunction(x, y, z) { }
-var args = [0, 1, 2];
-myFunction.apply(null, args);
- -

Con la spread syntax può essere scritto come:

- -
function myFunction(x, y, z) { }
-var args = [0, 1, 2];
-myFunction(...args);
- -

Qualsiasi argomento nell'elenco di argomenti può utilizzare la spread syntax e può essere utilizzato più volte.

- -
function myFunction(v, w, x, y, z) { }
-var args = [0, 1];
-myFunction(-1, ...args, 2, ...[3]);
- -

Apply for new

- -

When calling a constructor with {{jsxref("Operators/new", "new")}} it's not possible to directly use an array and apply (apply does a [[Call]] and not a [[Construct]]). However, an array can be easily used with new thanks to spread syntax:

- -
var dateFields = [1970, 0, 1];  // 1 Jan 1970
-var d = new Date(...dateFields);
-
- -

To use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application:

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

Spread in array literals

- -

A more powerful array literal

- -

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:

- -
var parts = ['shoulders', 'knees'];
-var lyrics = ['head', ...parts, 'and', 'toes'];
-// ["head", "shoulders", "knees", "and", "toes"]
-
- -

Just like spread for argument lists, ... can be used anywhere in the array literal and it can be used multiple times.

- -

Copiare un array

- -
var arr = [1, 2, 3];
-var arr2 = [...arr]; // like arr.slice()
-arr2.push(4);
-
-// arr2 becomes [1, 2, 3, 4]
-// arr remains unaffected
-
- -
-

Note: 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).

-
- -
var a = [[1], [2], [3]];
-var b = [...a];
-b.shift().shift(); // 1
-// Adesso anche l'array a è influenzato: [[], [2], [3]]
-
- -

Un modo migliore per concatenare gli array

- -

{{jsxref("Array.prototype.concat()")}} è spesso usato per concatenare un array alla fine di un array esistente. Senza la spread syntax questo è fatto così:

- -
var arr1 = [0, 1, 2];
-var arr2 = [3, 4, 5];
-// Append all items from arr2 onto arr1
-arr1 = arr1.concat(arr2);
- -

Con la spread syntax questo diventa:

- -
var arr1 = [0, 1, 2];
-var arr2 = [3, 4, 5];
-arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5]
-
- -

{{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ì:

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

Con la spread syntax questo diventa:

- - - -
var arr1 = [0, 1, 2];
-var arr2 = [3, 4, 5];
-arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2]
-
- -
-

Note: A differenza di unshift(), questo crea un nuovo arr1, e non modifica l'array originale arr1.

-
- -

Spread in object literals

- -

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.

- -

Lo Shallow-cloning (escluso il prototipo) o fusione di oggetti è ora possibile usando una sintassi più breve di {{jsxref("Object.assign()")}}.

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

Nota che {{jsxref("Object.assign()")}} attiva i setters mentre la spread syntax non lo fa.

- -

Nota che non è possibile sostituire o imitare la funzione {{jsxref("Object.assign()")}}:

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

Nell'esempio precedente, la spread syntax non funziona come previsto: estende una serie di argomenti nel letterale dell'oggetto, a causa del parametro rest.

- -

Solo per iterabili

- -

La spread syntax (diversa dal caso delle spread properties) può essere applicata solo agli oggetti iterabili:

- -
var obj = {'key1': 'value1'};
-var array = [...obj]; // TypeError: obj non è iterabile
-
- -

Diffusione con molti valori

- -

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.

- -

Rest syntax (parametri)

- -

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 rest parameters.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}Definito in diverse sezioni della specifica: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Definito in Object Initializer
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}Nessun cambiamento.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}Nessun cambiamento.
- -

Compatibilità con i browser

- - - -

{{Compat("javascript.operators.spread")}}

- -

Vedi anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

La parola chiave super viene usata per chiamare le funzioni dell'oggetto padre.

- -

Il super.prop ed espressioni con super[expr] sono valide in ogni  definizione di metodo sia nelle classi e oggetti literals.

- -

Sintassi

- -
super([arguments]); // chiama il costruttore padre.
-super.functionOnParent([arguments]);
-
- -

Descrizione

- -

Quando viene usata in un costruttore, la parola chiave super deve essere usata prima della parola chiave this. La parola chiave super può essere usata anche per chiamare funzioni dell'oggetto padre.

- -

Esempio

- -

Usare super nelle classi

- -

Questo pezzo di codice è preso da classes sample (live demo). super è chiamato per evitare la duplicazione del codice comune ad entrambi i costruttori Rectangle e Square.

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

Usare super con metodi statici

- -

Puoi usare super anche chiamare metodi statici.

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

Cancellare una proprietà del super causa eccezione

- -

Non puoi cancellare una proprietà della classe padre usando l' operatore delete e super.propsuper[esperssione], questo causerà un {{jsxref("ReferenceError")}}.

- -
class Base {
-  constructor() {}
-  foo() {}
-}
-class Derived extends Base {
-  constructor() {}
-  delete() {
-    delete super.foo;
-  }
-}
-
-new Derived().delete(); // ReferenceError: uso della delete con 'super'. 
- -

Super.prop non può sovrascrivere proprietà non scrivibili

- -

Quando si definisce una proprietà non riscrivibile con ad esempio {{jsxref("Object.defineProperty")}}, super non può modificarne il valore.

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

Uso di super.prop in oggetti literals

- -

Super può essere utilizzato anche nella initializzazione di oggetti con notazione letterale. In questo esempio, due oggetti definiscono un metodo. Nel secondo oggetto, super 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 obj2 con l'oggetto obj1, in modo che super sia in grado di trovare method1 in obj1.

- -
var obj1 = {
-  method1() {
-    console.log("method 1");
-  }
-}
-
-var obj2 = {
-  method2() {
-   super.method1();
-  }
-}
-
-Object.setPrototypeOf(obj2, obj1);
-obj2.method2(); // logs "method 1"
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-super-keyword', 'super')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}{{Spec2('ESDraft')}}
- -

Browser compatibili

- -

{{Compat("javascript.operators.super")}}

- -
- -

Gecko specific notes

- - - -

Vedi anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

La keyword di funzione this si comporta in modo leggermente differente in JavaScript rispetto ad altri linguaggi. Esistono inoltre alcune differenze tra strict mode e non-strict mode.

- -

Nella maggior parte dei casi, il valore di this è determinato da come la funzione viene invocata (chiamata). Il valore di this 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 bind per impostare il valore di this indipendentemente da come la funzione è invocata. ECMAScript 2015 ha introdotto le funzione a freccia ( arrow function ), in cui la keyword this viene lessicalmente incorporata nello scope corrente ( lo scope del contesto di esecuzione relativo al blocco corrente ).

- -

Sintassi

- -
this
- -

Contesto Globale

- -

Nel contesto di esecuzione globale (fuori da qualsiasi funzione), this si riferisce all'oggetto globale, sia che ci si trovi in strict mode,  sia che ci si trovi in non-strict mode.

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

Contesto di funzione

- -

All'interno di una funzione, il valore di this dipende da come la funzione è invocata.

- -

Chiamata semplice

- -
function f1(){
-  return this;
-}
-
-f1() === window; // global object
-
- -

In questo caso, il valore di this non viene impostato dalla chiamata. Visto che il codice non è in strict mode, il valore di this deve sempre essere un oggetto quindi viene impostato di default sull'oggetto globale.

- -
function f2(){
-  "use strict"; // see strict mode
-  return this;
-}
-
-f2() === undefined;
-
- -

In strict mode, il valore di this 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 null42"I am not this".

- -
Nota: Nel secondo esempio, this dovrebbe essere undefined, perchè f2 viene invocata senza specificare alcuna base (per esempio, window.f2()). Alcuni browser non hanno implementato questo orientamento, quando hanno deciso di supportare lo strict mode. Come risultato, questi browser restituivano, in modo non corretto, l'oggetto window.
- -

Funzioni Arrow

- -

Nelle funzioni arrow, this è assegnato lessicalmente, assume cioè il valore del contesto di esecuzione che contiene this. In codice globale punta all'oggetto globale:

- -
var globalObject = this;
-var foo = (() => this);
-console.log(foo() === globalObject); // true
- -

Non importa come foo sia invocato, this punterà all'oggetto globale. Questo è ancora valido se è chiamato come metodo di un oggetto (che solitamente punterebbe il valore di this sullo stesso) tramite chiamate dei metodi call o apply o bind

- -
// Call as a method of an object
-var obj = {foo: foo};
-console.log(obj.foo() === globalObject); // true
-
-// Attempt to set this using call
-console.log(foo.call(obj) === globalObject); // true
-
-// Attempt to set this using bind
-foo = foo.bind(obj);
-console.log(foo() === globalObject); // true
- -

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.

- -
// Create obj with a method bar that returns a function that
-// returns its this. The returned function is created as 
-// an arrow function, so its this is permanently bound to the
-// this of its enclosing function. The value of bar can be set
-// in the call, which in turn sets the value of the 
-// returned function.
-var obj = { bar : function() {
-                    var x = (() => this);
-                    return x;
-                  }
-          };
-
-// Call bar as a method of obj, setting its this to obj
-// Assign a reference to the returned function to fn
-var fn = obj.bar();
-
-// Call fn without setting this, would normally default
-// to the global object or undefined in strict mode
-console.log(fn() === obj); // true
- -

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

- -

In the above, the function(call it anonymous function A) assigned to obj.bar returns another function(call it anonymous function B) that is created as an arrow function. As a result, function B's  this is permanently set to the this of obj.bar (function A)when called. When the returned function(function B) is called, its this will always be what it was set to initially. In the above code example, function B's this is set to function A's this which is obj, so it remains set to obj even when called in a manner that would normally set its this to undefined or the global object (or any other method as in the previous example in the global execution context).

- -

Come metodo di un oggetto

- -

Quando una funzione viene invocata come metodo di un oggetto, il this, all'interno della funzione, viene impostato sull'oggetto di cui la funzione è metodo.

- -

Nell'esempio seguente, quando o.f() viene invocata, all'interno della funzione this è associato all'oggetto o.

- -
var o = {
-  prop: 37,
-  f: function() {
-    return this.prop;
-  }
-};
-
-console.log(o.f()); // logs 37
-
- -

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 f, nel corso della definizione di o. Tuttavia, avremmo potuto facilmente definire la funzione prima, per poi associarla a o.f. Il risultato sarebbe stato lo stesso:

- -
var o = {prop: 37};
-
-function independent() {
-  return this.prop;
-}
-
-o.f = independent;
-
-console.log(o.f()); // logs 37
-
- -

Questo dimostra che la cosa più importante è che la funzione venga invocata dal membro f di o.

- -

In modo analogo, l'associazione di this è influenzata solo dal membro più vicino. Nell'esempio seguente, quando invochiamo la funzione, la invochiamo come metodo g dell'oggetto o.b. Questa volta, durante l'esecuzione, this, all'interno della funzione, sarà associata ad o.b. Il fatto che l'oggetto sia, esso stesso, un membro di o non ha alcuna conseguenza; la sola cosa che conti è il riferimento più immediato.

- -
o.b = {g: independent, prop: 42};
-console.log(o.b.g()); // logs 42
-
- -

this nella prototype chain dell'oggetto

- -

La stessa notazione è valida per i metodi definiti altrove nella prototype chain dell'oggetto. Se il metodo è sulla prototype chain di un oggetto, this si riferisce all'oggetto su cui il metodo è stato chiamato, come se il metodo appartenesse all'oggetto.

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

in questo esempio, l'oggetto assegnato alla variabile p non ha definita una proprietà f, la eredita dal suo prototipo. Non ha importanza che il controllo per f trovi eventualmente un membro con quel nome in o; il controllo è cominciato con un riferimento a p.f, quindi this all'interno della funzione assume il valore dell'oggetto a cui p si riferisce. Cioè, dal momento che f è chiamata come metodo di p, la parola chiave this al suo interno si riferisce a p. Questa è una interessante caratteristica dell'ereditarietà dei prototipi di javascript.

- -

this all'interno di metodi getter o setter

- -

Ancora, la stessa notazione è valida quando una funzione è invocata all'interno di metodi get o set. In una funzione usata come getter o setter this viene collegata all'oggetto dal quale la proprietà è settata o ricavata.

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

Come costruttore

- -

Quando una funzione è usata come un costruttore (tramite la parola chiave new), this è collegata al nuovo oggetto che viene costruito.

- -

Nota: mentre di default un costruttore restituisce l'oggetto riferenziato da this, può invece restituire qualche altro oggetto (se il valore di ritorno non è un oggetto, allora viene restituito l'oggetto this).

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

Nell'ultimo esempio (C2), dal momento che è stato restituito un oggetto durante la costruzione, il nuovo oggetto a cui this era collegato viene semplicemente scartato. (Questo rende essenzialmente l'assegnazione "this.a = 37;" codice inutile. Non lo è in senso stretto, in quanto viene eseguito, ma può essere eliminato senza conseguenze).

- -

I metodi call e apply

- -

Dove una funzione usa la parola chiave this, il suo valore può essere collegato ad un qualsivoglia oggetto nella chiamata usando i metodi call o apply che tutte le funzioni ereditano da Function.prototype. 

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

Notare che con call e apply, se il valore passato tramite this non è un oggetto, viene eseguito un tentativo di convertire tale valore in oggetto usando l'operazione interna ToObject. pertanto, se il valore passato è un primitivo come 7 o 'foo', questo verrà convertito ad Object usando il relativo costruttore, quindi il valore primitivo 7 viene convertito  come new Number(7) e la stringa 'foo' viene convertita come new String('foo'), per esempio:

- -
function bar() {
-  console.log(Object.prototype.toString.call(this));
-}
-
-bar.call(7); // [object Number]
-
- -

Il metodo bind

- -

ECMAScript 5 ha introdotto Function.prototype.bind. Chiamare f.bind(someObject) crea una nuova funzione con lo stesso corpo e visibità di f, ma nella funzione originale si trova la parola chiave this, nella nuova funzione viene permanentemente collegato al primo argomento passato alla chiamata del metodo bind, ignorando come la funzione stessa venga usata. 

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

Come handler degli eventi del DOM

- -

Quando una funzione viene usata come handler di eventi, i suoi riferimenti this sono puntati all'elemento che ha originato l'evento (alcuni Browser non seguono queste convenzioni per i listeners agguinti dinamicamente tramite metodi diversi da addEventListener).

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

In un handler di eventi "in-line"

- -

quando il codice è chiamato da un handler in-line, this punta all'elemento DOM sul quale il listener è posizionato:

- -

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

- -
<button onclick="alert(this.tagName.toLowerCase());">
-  Show this
-</button>
-
- -

Sopra, alert mostra 'button'. Notare comunque che this assume tale valore solo al di fuori di una funzione:

- -

 

- -
<button onclick="alert((function(){return this}()));">
-  Show inner this
-</button>
-
- -

 

- -

in questo caso, nella funzione interna, this non punta all'elemento DOM quindi restituisce l'oggetto globale/window (cioè l'oggetto di default in modalità non-strict, in cui this non viene impostato dalla chiamata)

- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

 

- -

Compatibilità dei browser

- -

{{CompatibilityTable}}

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

 

- -

Vedere Anche

- - 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 ---- -
{{jsSidebar("Operators")}}
- -

La parola chiave yield è usata per mettere in pausa e far ripartire un generatore di funzione ({{jsxref("Statements/function*", "function*")}} or legacy generator function).

- -

Sintassi

- -
[rv] = yield [expression];
- -
-
espressione
-
Definisce il valore da ritornare dalla funzione generatore attraverso the iterator protocol. Se omesso, undefined viene restituito.
-
rv
-
Permette che il generatore catturi il valore dell'espressione per usarlo al prossimo avvio dell'esecuzione.
-
- -

Descrizione

- -

The yield keyword causes generator function execution to pause and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword.

- -

The yield keyword actually returns an IteratorResult object with two properties, value and done. The value property is the result of evaluating the yield expression, and done is a Boolean indicating whether or not the generator function has fully completed.

- -

Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. Each time the generator's next() method is called, the generator resumes execution and runs until it reaches one of the following:

- - - -

If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's next yield operation.

- -

Between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to {{jsxref("Generator.prototype.next()")}}, generators offer enormous power and control.

- -

Examples

- -

The following code is the declaration of an example generator function, along with a helper function.

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

Once a generator function is defined, it can be used by constructing an iterator as shown.

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

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Firefox-specific notes

- - - -

See also

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