From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../global_objects/function/apply/index.html | 250 +++++++++++++++++++ .../global_objects/function/arguments/index.html | 92 +++++++ .../global_objects/function/arity/index.html | 26 ++ .../global_objects/function/bind/index.html | 277 +++++++++++++++++++++ .../global_objects/function/call/index.html | 175 +++++++++++++ .../reference/global_objects/function/index.html | 237 ++++++++++++++++++ .../global_objects/function/length/index.html | 87 +++++++ 7 files changed, 1144 insertions(+) create mode 100644 files/it/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/arity/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/length/index.html (limited to 'files/it/web/javascript/reference/global_objects/function') diff --git a/files/it/web/javascript/reference/global_objects/function/apply/index.html b/files/it/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..1c0d04272d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,250 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +tags: + - JavaScript + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
+

{{JSRef}}

+ +

Il metodo apply() chiama una funzione passandole il "this" ed i parametri forniti sottoforma di array (o array-like object).

+ +

Nota: Mentre la sintassi di questa funzione è quasi completamente identica a quella di {{jsxref("Function.call", "call()")}}, la fondamentale differenza è che call() accetta una lista di parametri, mentre apply() accetta un singolo array contenente una lista di parametri.

+ +

Sintassi

+ +
fun.apply(thisArg, [argsArray])
+ +

Parametri

+ +
+
thisArg
+
Il valore del this da fornire alla chiamata a fun. Nota che questo potrebbe non essere l'effettivo valore visto dal metodo: se il metodo non è eseguito in {{jsxref("Strict_mode", "strict mode", "", 1)}}, {{jsxref("null")}} ed {{jsxref("undefined")}} saranno rimpiazzati dall'oggetto globale.
+
argsArray
+
Un array-like object che specifica i parametri con la quale la funzione fun deve essere chiamata. Può essere anche {{jsxref("null")}} o {{jsxref("undefined")}} nel caso nessun parametro dovesse essere passato. A partire da ECMAScript 5 questi parametri possono essere un qualunque array-like object invece di un semplice array. Vedi sotto per le {{anch("Browser_compatibility", "compatibilità nei browser")}}.
+
+ +

Descrizione

+ +

this solitamente si riferisce all'oggetto corrente, ma grazie ad apply è possibile scrivere un metodo una sola volta e riusarlo più volte su oggetti differenti passando ad apply, appunto, un this differente. Cosi viene eliminata la necessità di riscrivere di nuovo lo stesso metodo per un oggetto diverso.

+ +

apply è molto simile a {{jsxref("Function.call", "call()")}}, eccezion fatta per il modo in cui i parametri vengono passati. Puoi utilizzare un array di parametri invece della solita lista. Con apply, ad esempio, puoi utilizzare il seguente array literal: fun.apply(this, ['eat', 'bananas']), o il seguente oggetto {{jsxref("Array")}}: fun.apply(this, new Array('eat', 'bananas')).

+ +

Puoi anche utilizzare {{jsxref("Functions/arguments", "arguments")}} per il parametro argsArrayarguments è una variabile locale di tutte le funzioni. Può essere utilizzata per tutti i parametri non specificati dell'oggetto chiamato. In più, non è necessario che si conoscano i parametri dell'oggetto chiamato quando si utilizza apply.

+ +

Da ECMAScript 5 puoi anche usare qualunque tipo di array-like object. Ad esempio puoi utilizzare un {{domxref("NodeList")}} o un oggetto come { 'length': 2, '0': 'eat', '1': 'bananas' }.

+ +

{{note("La maggior parte dei browser, incluso Chrome 14 ed Internet Explorer 9, non accetto array-like objects e lanceranno una eccezione.")}}

+ +

Esempi

+ +

Utilizzare apply per concatenare costruttori

+ +

Puoi utilizzare apply per concatenare {{jsxref("Operators/new", "costruttori", "", 1)}} per un oggetto, in maniera simile a Java. Nel seguente esempio creeremo una {{jsxref("Function")}} globale chiamata construct, che ti permetterà di utilizzare un array-like object con un costruttore anziché una lista di argomenti.

+ +
Function.prototype.construct = function (aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +

Note: Il metodo Object.create() usato nell'esempio sovrastante è relativamente nuovo. Per un alternativa che utilizza le closures considera questo pezzo di codice:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+ +

Esempio d'uso:

+ +
function MyConstructor() {
+  for (var nProp = 0; nProp < arguments.length; nProp++) {
+    this['property' + nProp] = arguments[nProp];
+  }
+}
+
+var myArray = [4, 'Hello world!', false];
+var myInstance = MyConstructor.construct(myArray);
+
+console.log(myInstance.property1);                // logs 'Hello world!'
+console.log(myInstance instanceof MyConstructor); // logs 'true'
+console.log(myInstance.constructor);              // logs 'MyConstructor'
+
+ +

Note: Il metodo non nativo Function.construct non funzionerà con alcuni costruttori nativi (come {{jsxref("Date")}}). In questi casi devi usare {{jsxref("Function.prototype.bind")}}. Immagina ad esempio di avere un array come il seguente da utilizzare con il costruttore {{jsxref("Global_Objects/Date", "Date")}}: [2012, 11, 4]; In questo caso dovresti scrivere qualcosa come: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — ad ogni modo questo non è il miglior modo di fare le cose e non andrebbe mai usato in produzione.

+ +

Utilizzare apply combinato alle funzioni built-in

+ +

Un intelligente uso di apply ti permette di utilizzare delle funzioni built-in per dei compiti che altrimenti sarebbero stati fatti, nel caso sottostante, ciclando l'array e scorrendo ogni suo elemento e sottoponendolo a dei controlli. L'esempio seguente dimostra come trovare il massimo / minimo valore all'interno di un array utilizzando Math.max/Math.min.

+ +
// min/max number in an array
+var numbers = [5, 6, 2, 3, 7];
+
+// using Math.min/Math.max apply
+var max = Math.max.apply(null, numbers);
+// This about equal to Math.max(numbers[0], ...)
+// or Math.max(5, 6, ...)
+
+var min = Math.min.apply(null, numbers);
+
+// vs. simple loop based algorithm
+max = -Infinity, min = +Infinity;
+
+for (var i = 0; i < numbers.length; i++) {
+  if (numbers[i] > max) {
+    max = numbers[i];
+  }
+  if (numbers[i] < min) {
+    min = numbers[i];
+  }
+}
+
+ +

Ma tieni a mente che nell'usare apply in questo modo si corre il rischio di superare il limite imposto dal motore JavaScript degli argomenti che possono essere passati ad una funzione.
+ Le conseguenze nel fare ciò variano da motore a motore (ad esempio JavaScriptCore ha il limite settato a mano di 65536 parametri), perché il limite non è specificato. Alcuni motori lanceranno una eccezione. Altri invece limiteranno arbitrariamente il numero dei parametri passati alla funzione su cui viene usato il metodo apply(). (Un esempio di quest'ultimo caso potrebbe essere quello di un motore che ha questo limite settato a 4 e, nell'esempio sovrastante, gli unici parametri che effettivamente saranno passati alla funzione saranno 5, 6, 2, 3, piuttosto che l'intero array.) Una decisione saggia, nel caso si prevede la possibilità di raggiungere un enorme numero di parametri, sarebbe quella di parzializzare il numero di parametri per lotti:

+ +
function minOfArray(arr) {
+  var min = Infinity;
+  var QUANTUM = 32768;
+
+  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
+    var submin = Math.min.apply(null, arr.slice(i, Math.min(i+QUANTUM, len)));
+    min = Math.min(submin, min);
+  }
+
+  return min;
+}
+
+var min = minOfArray([5, 6, 2, 3, 7]);
+
+ +

Usare apply come "monkey-patch"

+ +

L'attività del "monkey-patching" consiste nel modificare il funzionamento di un metodo senza dover andare a mettere mano al codice sorgente (cosa da evitare sempre e comunque). Difatti Apply può rivelarsi il modo migliore di modificare il funzionamento, ad esempio, di una funzione interna a Firefox o di una qualunque altra libreria JS. Data una funzione someobject.foo, è possibile modificarne il funzionamento in questo modo:

+ +
var originalfoo = someobject.foo;
+someobject.foo = function() {
+  // Do stuff before calling function
+  console.log(arguments);
+  // Call the function as it would have been called normally:
+  originalfoo.apply(this, arguments);
+  // Run stuff after, here.
+}
+
+ +

Questo metodo ritorna particolarmente utile quando vuoi debuggare eventi e interfacce con qualcosa che non espone API come i diversi eventi .on([event]... (usabili anche dal Devtools Inspector).

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

Vedi anche

+ + +
diff --git a/files/it/web/javascript/reference/global_objects/function/arguments/index.html b/files/it/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..949e5f9cdb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,92 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +tags: + - Deprecated + - Function + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +
{{JSRef}} {{deprecated_header}}
+ +

La proprieta' function.arguments fa riferimento ad un oggetto simile ad un array corrispondente ai parametri passati ad una funzione. Usa questa semplice variabile {{jsxref("Functions/arguments", "arguments")}} invece. Questa proprieta' non e' disponibile in strict mode.

+ +

Descrizione

+ +

La sintassi function.arguments e' deprecata. Il metodo consigliato per accedere all'oggetto {{jsxref("Functions/arguments", "arguments")}}, disponibile all'interno delle funzioni e' semplicemente mediante l'utilizzo di {{jsxref("Functions/arguments", "arguments")}}.

+ +

In caso di ricorsione, per esempio, se la funzione f e' presente diverse volte nello stack, il valore di f.arguments rappresenta i parametri corrispondenti alla chiamata alla funzione piu' recente.

+ +

Il valore della proprieta' arguments e' normalmente null se non c'e' una sua chiamata durante l'esecuzione della funzione (ovvero quando la funzione e' stata chiamata ma non ha ancora ritornato nessun valore).

+ +

Esempi

+ +
function f(n) { g(n - 1) }
+
+function g(n) {
+  console.log('before: ' + g.arguments[0])
+  if (n > 0) { f(n) }
+  console.log('after: ' + g.arguments[0])
+}
+
+f(2)
+
+console.log('returned: ' + g.arguments)
+
+// Output
+
+// before: 1
+// before: 0
+// after: 0
+// after: 1
+// returned: null
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0. Deprecated in favor of {{jsxref("Functions/arguments", "arguments")}} in ES3.
{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}{{Spec2('ES5.1')}}{{jsxref("Functions/arguments", "arguments")}} object
{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}{{Spec2('ES6')}}{{jsxref("Functions/arguments", "arguments")}} object
{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}{{Spec2('ESDraft')}}{{jsxref("Functions/arguments", "arguments")}} object
+ +

Compatibilita' Browser

+ +
+ + +

{{Compat("javascript.builtins.Function.arguments")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/arity/index.html b/files/it/web/javascript/reference/global_objects/function/arity/index.html new file mode 100644 index 0000000000..fec2d9e988 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/arity/index.html @@ -0,0 +1,26 @@ +--- +title: Function.arity +slug: Web/JavaScript/Reference/Global_Objects/Function/arity +translation_of: Archive/Web/JavaScript/Function.arity +--- +

{{JSRef}}{{Obsolete_Header}}

+ +
+

La proprieta' arity ritornava il numero di parametri richiesta da una funzione. Ad ogni modo non esiste piu' ed e' stata rimpiazzata dalla proprieta' {{JSxRef("Function.prototype.length")}}.

+
+ +

Specifiche

+ +

Implementato in JavaScript 1.2. Deprecato in JavaScript 1.4.

+ +

Compatibilita' Browser

+ + + +

{{Compat("javascript.builtins.Function.arity")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/bind/index.html b/files/it/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..38187ac5e6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,277 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+ +

Il metodo bind() crea una nuova funzione che, quando chiamata, ha parola chiave this impostata sul valore fornito, con una data sequenza di argomenti che precede quella fornita quando viene chiamata la nuova funzione

+ +

{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}

+ + + +

Sintassi

+ +
function.bind(thisArg[, arg1[, arg2[, ...]]])
+ +

Parametri

+ +
+
thisArg
+
Il valore va passato come parametro alla funzione target quando viene chiamata la funzione associata. Il valore viene ignorato se la funzione associata viene costruita utilizzando l'operatore {{jsxref("Operators/new", "new")}}. Quando si utilizza bind per creare una funzione (fornita come callback) all'interno di un setTimeout, qualsiasi valore primitivo passato come thisArg viene convertito in oggetto. Se non vengono forniti argomenti per vincolarlo, l'esecuzione viene considerata come thisArg per la nuova funzione.
+
arg1, arg2, ...
+
Argomenti da anteporre agli argomenti forniti alla funzione associata quando si richiama la funzione di destinazione.
+
+ +

Valore restituito

+ +

Una copia della funzione data con specificato this valore e gli argomenti iniziali.

+ +

Descrizione

+ +

La funzione bind() crea una nuova funzione associata (BF, bound function). Un BF è un exotic function object (oggetto funzione esotico, un termine di ECMAScript 2015) che racchiude l'oggetto funzione originale. Chiamare un BF generalmente comporta l'esecuzione della sua funzione wrapped (avvolta).
+ Un BF ha le seguenti proprietà interne:

+ + + +

Quando viene chiamata la funzione associata, chiama il metodo interno [[Call]] su [[BoundTargetFunction]], con i seguenti argomenti call(boundThis, ...args). Dove, boundThis è [[BoundThis]], args è [[BoundArguments]] seguito dagli argomenti passati dalla chiamata alla funzione.

+ +

Una funzione associata (bound function) può anche essere costruita usando l'operatore new: agendo in tal modo si comporta come se la funzione obiettivo fosse stata invece costruita. Il valore this fornito viene ignorato, mentre gli argomenti preposti sono forniti alla funzione emulata.

+ +

Esempi

+ +

Creare una funzione associata

+ +

L'uso più semplice di bind() è di creare una funzione che, indipendentemente da come viene chiamata, viene chiamata con un particolare valore. Un errore comune per i nuovi programmatori JavaScript consiste nell'estrarre un metodo da un oggetto, in seguito chiamare tale funzione e aspettarsi che utilizzi l'oggetto originale come tale (ad esempio, utilizzando tale metodo nel codice basato sul callback). Senza particolare cura, tuttavia, l'oggetto originale viene solitamente perso. La creazione di una funzione associata dalla funzione, utilizzando l'oggetto originale, risolve in modo chiaro questo problema:

+ +
this.x = 9;    // questo si riferisce all'oggetto "finestra" globale qui nel browser
+var module = {
+  x: 81,
+  getX: function() { return this.x; }
+};
+
+module.getX(); // 81
+
+var retrieveX = module.getX;
+retrieveX();
+// returns 9 - restituisce 9 - La funzione viene richiamata nell'ambito globale
+
+// Create a new function with 'this' bound to module
+// Crea una nuova funzione con 'this' associato al modulo
+// I nuovi programmatori potrebbero confondere il
+// global var x con la proprietà del modulo x var boundGetX = retrieveX.bind(module);
+boundGetX(); // 81
+
+ +

Funzioni parzialmente applicate

+ +

Il prossimo uso più semplice di bind() è quello di creare una funzione con argomenti iniziali pre-specificati. Questi argomenti (se presenti) seguono il valore fornito e vengono quindi inseriti all'inizio degli argomenti passati alla funzione di destinazione, seguiti dagli argomenti passati alla funzione associata, ogni volta che viene chiamata la funzione associata.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+// Crea una funzione con un argomento principale preimpostato
+var leadingThirtysevenList = list.bind(null, 37);
+
+var list2 = leadingThirtysevenList();
+// [37]
+
+var list3 = leadingThirtysevenList(1, 2, 3);
+// [37, 1, 2, 3]
+
+ +

Con setTimeout

+ +

Di default all'interno di {{domxref("window.setTimeout()")}}, la parola chiave this verrà impostata sull'oggetto {{ domxref("window") }} (or global). Quando si lavora con metodi di classe che richiedono questo this riferimento alle istanze di classe, è possibile associarlo esplicitamente alla funzione di callback, al fine di mantenere l'istanza.

+ +
function LateBloomer() {
+  this.petalCount = Math.floor(Math.random() * 12) + 1;
+}
+
+// Dichiarare apertura dopo un ritardo di 1 secondo
+LateBloomer.prototype.bloom = function() {
+  window.setTimeout(this.declare.bind(this), 1000);
+};
+
+LateBloomer.prototype.declare = function() {
+  console.log('Sono un bel fiore con ' +
+    this.petalCount + ' petali!');
+};
+
+var flower = new LateBloomer();
+flower.bloom();
+// dopo 1 secondo, attiva il metodo 'declare'
+ +

Funzioni associate utilizzate come costruttori

+ +
+

Warning: Questa sezione dimostra capacità JavaScript e documenta alcuni casi limite del metodo bind(). I metodi mostrati di seguito non sono il modo migliore di fare le cose e probabilmente non dovrebbero essere usati in nessun ambiente di produzione.

+
+ +

Le funzioni associate sono automaticamente utilizzabili con l'operatore {{jsxref("Operators/new", "new")}} per costruire nuove istanze create dalla funzione target. Quando una funzione associata viene utilizzata per costruire un valore, la condizione viene ignorata. Tuttavia, gli argomenti forniti sono ancora preposti alla chiamata del costruttore:

+ +
function Point(x, y) {
+  this.x = x;
+  this.y = y;
+}
+
+Point.prototype.toString = function() {
+  return this.x + ',' + this.y;
+};
+
+var p = new Point(1, 2);
+p.toString(); // '1,2'
+
+// non supportato nel polyfill di seguito,
+// funziona bene con il bind nativo:
+
+var YAxisPoint = Point.bind(null, 0/*x*/);
+
+
+var emptyObj = {};
+var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
+
+var axisPoint = new YAxisPoint(5);
+axisPoint.toString(); // '0,5'
+
+axisPoint instanceof Point; // true
+axisPoint instanceof YAxisPoint; // true
+new Point(17, 42) instanceof YAxisPoint; // true
+
+ +

Note that you need do nothing special to create a bound function for use with {{jsxref("Operators/new", "new")}}. The corollary is that you need do nothing special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using {{jsxref("Operators/new", "new")}}.

+ +
// Example can be run directly in your JavaScript console
+// ...continuing from above
+
+// Can still be called as a normal function
+// (although usually this is undesired)
+YAxisPoint(13);
+
+emptyObj.x + ',' + emptyObj.y;
+// >  '0,13'
+
+ +

If you wish to support the use of a bound function only using {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.

+ +

Creating shortcuts

+ +

bind() is also helpful in cases where you want to create a shortcut to a function which requires a specific this value.

+ +

Take {{jsxref("Array.prototype.slice")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

+ +
var slice = Array.prototype.slice;
+
+// ...
+
+slice.apply(arguments);
+
+ +

With bind(), this can be simplified. In the following piece of code, slice is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the this value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional apply() calls can be eliminated:

+ +
// same as "slice" in the previous example
+var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.apply.bind(unboundSlice);
+
+// ...
+
+slice(arguments);
+
+ +

Polyfill

+ +

You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.

+ +
if (!Function.prototype.bind) {
+  Function.prototype.bind = function(oThis) {
+    if (typeof this !== 'function') {
+      // closest thing possible to the ECMAScript 5
+      // internal IsCallable function
+      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
+    }
+
+    var aArgs   = Array.prototype.slice.call(arguments, 1),
+        fToBind = this,
+        fNOP    = function() {},
+        fBound  = function() {
+          return fToBind.apply(this instanceof fNOP
+                 ? this
+                 : oThis,
+                 aArgs.concat(Array.prototype.slice.call(arguments)));
+        };
+
+    if (this.prototype) {
+      // Function.prototype doesn't have a prototype property
+      fNOP.prototype = this.prototype;
+    }
+    fBound.prototype = new fNOP();
+
+    return fBound;
+  };
+}
+
+ +

Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are:

+ + + +

If you choose to use this partial implementation, you must not rely on those cases where behavior deviates from ECMA-262, 5th edition! With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when bind() is widely implemented according to the specification.

+ +

Please check https://github.com/Raynos/function-bind for a more thorough solution!

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function.bind")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/call/index.html b/files/it/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..54acd401ca --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,175 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +

Il metodo call() esegue una funzione con un dato valore this e argomenti passati singolarmente.

+ +
+

Note: Mentre la sintassi di questa funzione è quasi identica a quella di {{jsxref("Function.prototype.apply", "apply()")}}, la differenza fondamentale è che call() accetta una lista di argomenti mentre apply() accetta un singolo array di argomenti.

+
+ +
{{EmbedInteractiveExample("pages/js/function-call.html")}}
+ + + +

Sintassi

+ +
func.call([thisArg[, arg1, arg2, ...argN]])
+ +

Parametri

+ +
+
thisArg {{optional_inline}}
+
+

Il valore da usare come this quando si esegue func.

+ +
+

Attenzione: In certi casi, thisArg potrebbe non essere il valore reale visto dal metodo.

+ +

Se il metodo è una funzione in {{jsxref("Strict_mode", "non-strict mode", "", 1)}}, {{jsxref("Global_Objects/null", "null")}} e {{jsxref("Global_Objects/undefined", "undefined")}} sarà sostituito dall'oggetto globale e i valori di tipo primitiva verranno convertiti in oggetti.

+
+
+
arg1, arg2, ...argN {{optional_inline}}
+
Argomenti per la funzione.
+
+ +

Valore restituito

+ +

Il risultato dell'esecuzione della funzione con il this e gli argomenti specificati.

+ +

Descrizione

+ +

Il metodo call() consente a una funzione/metodo appartenente a un oggetto di essere essere assegnata e chiamata per un oggetto diverso..

+ +

call() fornisce un nuova valore di this alla funzione/metodo. Con call(), si può scrivere un metodo una volta ed ereditarlo in un altro oggetto senza dover riscrivere il metodo per il nuovo oggetto.

+ +

Esempi

+ +

Usare call per collegare costruttori per un oggetto

+ +

Si può usare call per collegare costruttori per un oggetto (simile a Java).

+ +

Nell'esempio seguente, il costruttore per l'oggetto Product è definito con 2 parametri: name e price.

+ +

Due altre funzioni, Food e Toy, invocano Product, passando this, name, e price. Product inizializza le proprietà name e price. Entrambe le funzioni specializzate definiscono la category.

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+const cheese = new Food('feta', 5);
+const fun = new Toy('robot', 40);
+
+ +

Usare call per invocare una funzione anonima

+ +

In questo esempio, viene create una funzione anonima e usato call per invocarla su ogni oggetto di un array.

+ +

Lo scopo principale della funzione anonima qui è di aggiungere una funzione print o ogni oggetto il quale è in grado di stampare il corretto indice dell'oggetto nell'array.

+ +
+

Passare l'oggetto come valore this non è strettamente necessario ma è fatto a scopo esplicativo.

+
+ +
const animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (let i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

Usare call per invocare una funzione e specificare il contesto per  'this'

+ +

Nell'esempio sotto, quando viene eseguita greet, il valore di this verrà legato all'oggetto obj.

+ +
function greet() {
+  const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
+  console.log(reply);
+}
+
+const obj = {
+  animal: 'cats', sleepDuration: '12 and 16 hours'
+};
+
+greet.call(obj);  // cats typically sleep between 12 and 16 hours
+
+ +

Usare call per invocare una funzione senza specificare il primo parametro

+ +

Nell'esempio sotto, viene invocata la funzione display senza passare il primo parametro. Se il primo parametro non è passato il valore di this è legato all'oggetto globale.

+ +
var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+ +
+

Attenzione: In strict mode il valore di this sarà undefined. Vedere sotto.

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+ +

Specifiche

+ + + + + + + + + + + + +
Specifiche
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Function.call")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/index.html b/files/it/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..4ef63fb80b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,237 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

+ +

gge

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Description

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +
+

Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Properties and Methods of Function

+ +

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function prototype object

+ +

Properties

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

Methods

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

Function instances

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

A recursive shortcut to massively modify the DOM

+ +

Creating functions with the Function constructor is one of the ways to dynamically create an indeterminate number of new objects with some executable code into the global scope from a function. The following example (a recursive shortcut to massively modify the DOM) is impossible without the invocation of the Function constructor for each new query if you want to avoid closures.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
+<script type="text/javascript">
+var domQuery = (function() {
+  var aDOMFunc = [
+    Element.prototype.removeAttribute,
+    Element.prototype.setAttribute,
+    CSSStyleDeclaration.prototype.removeProperty,
+    CSSStyleDeclaration.prototype.setProperty
+  ];
+
+  function setSomething(bStyle, sProp, sVal) {
+    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
+        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
+        aNodeList = bStyle ? this.cssNodes : this.nodes;
+
+    if (bSet && bStyle) { aArgs.push(''); }
+    for (
+      var nItem = 0, nLen = this.nodes.length;
+      nItem < nLen;
+      fAction.apply(aNodeList[nItem++], aArgs)
+    );
+    this.follow = setSomething.caller;
+    return this;
+  }
+
+  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
+  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
+  function getSelectors() { return this.selectors; };
+  function getNodes() { return this.nodes; };
+
+  return (function(sSelectors) {
+    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
+    oQuery.selectors = sSelectors;
+    oQuery.nodes = document.querySelectorAll(sSelectors);
+    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
+    oQuery.attributes = setAttribs;
+    oQuery.inlineStyle = setStyles;
+    oQuery.follow = getNodes;
+    oQuery.toString = getSelectors;
+    oQuery.valueOf = getNodes;
+    return oQuery;
+  });
+})();
+</script>
+</head>
+
+<body>
+
+<div class="testClass">Lorem ipsum</div>
+<p>Some text</p>
+<div class="testClass">dolor sit amet</div>
+
+<script type="text/javascript">
+domQuery('.testClass')
+  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
+  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
+</script>
+</body>
+
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

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

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/length/index.html b/files/it/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..6e305fb3ed --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,87 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

La proprietà length indica il numero di parametri che la funzione si aspetta di ricevere.

+ +

{{EmbedInteractiveExample("pages/js/function-length.html")}}

+ + + +
{{js_property_attributes(0,0,1)}}
+ +

Description

+ +

length è una proprietà di un oggetto {{jsxref("Function")}} che indica quanti argomenti la funzione si aspetta, cioè il numero di parametri formali. Questo numero esclude il {{jsxref("rest_parameters", "rest parameter", "", 1)}} e include solo i parametri prima del primo con un valore predefinito. Al contrario, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} è locale a una funzione e fornisce il numero di argomenti effettivamente passati alla funzione.

+ +

Data property of the Function constructor

+ +

Il costruttore  {{jsxref("Function")}} è esso stesso un oggetto {{jsxref("Function")}}. La sua proprietà length ha valore 1. Gli attributi delle proprietà sono: Writable: false, Enumerable: false, Configurable: false.

+ +

Property of the Function prototype object

+ +

La proprietà length del prototype di un oggetto {{jsxref("Function")}} ha valore 0.

+ +

Examples

+ +
console.log(Function.length); /* 1 */
+
+console.log((function()        {}).length); /* 0 */
+console.log((function(a)       {}).length); /* 1 */
+console.log((function(a, b)    {}).length); /* 2 etc. */
+
+console.log((function(...args) {}).length);
+// 0, rest parameter is not counted
+
+console.log((function(a, b = 1, c) {}).length);
+// 1, only parameters before the first one with
+// a default value is counted
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}Gli attributi configurabili di queste proprietà diventano true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function.length")}}

+
+ +

See also

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