From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../functions/arguments/caller/index.html | 93 ++++ .../reference/functions/arguments/index.html | 211 +++++++ .../functions/arguments/length/index.html | 117 ++++ .../javascript/reference/functions/get/index.html | 217 ++++++++ .../web/javascript/reference/functions/index.html | 617 +++++++++++++++++++++ .../reference/functions/parameters_rest/index.html | 156 ++++++ 6 files changed, 1411 insertions(+) create mode 100644 files/ca/web/javascript/reference/functions/arguments/caller/index.html create mode 100644 files/ca/web/javascript/reference/functions/arguments/index.html create mode 100644 files/ca/web/javascript/reference/functions/arguments/length/index.html create mode 100644 files/ca/web/javascript/reference/functions/get/index.html create mode 100644 files/ca/web/javascript/reference/functions/index.html create mode 100644 files/ca/web/javascript/reference/functions/parameters_rest/index.html (limited to 'files/ca/web/javascript/reference/functions') diff --git a/files/ca/web/javascript/reference/functions/arguments/caller/index.html b/files/ca/web/javascript/reference/functions/arguments/caller/index.html new file mode 100644 index 0000000000..b0a6afdf3e --- /dev/null +++ b/files/ca/web/javascript/reference/functions/arguments/caller/index.html @@ -0,0 +1,93 @@ +--- +title: arguments.caller +slug: Web/JavaScript/Reference/Functions/arguments/caller +translation_of: Archive/Web/JavaScript/arguments.caller +--- +
{{jsSidebar("Functions")}}
+ +

La propietat obsoleta arguments.caller solia proporcionar la funció que invoca la funció que s'està executant en aquest moment. Aquesta propietat s'ha eleminitat i ja no funciona.

+ +

Descripció

+ +

La propietat ja no és troba disponible, però encara es pot utilitzar {{jsxref("Function.caller")}}.

+ +
function whoCalled() {
+   if (whoCalled.caller == null)
+      console.log('I was called from the global scope.');
+   else
+      console.log(whoCalled.caller + ' called me!');
+}
+ +

Exemples

+ +

El codi següent s'utilitzava per comprovar el valor de arguments.caller en una funció, però ja no funciona.

+ +
function whoCalled() {
+   if (arguments.caller == null)
+      console.log('I was called from the global scope.');
+   else
+      console.log(arguments.caller + ' called me!');
+}
+
+ +

Especificacions

+ +

No forma part de cap estàndard. Implementat en JavaScript 1.1 i eliminat en {{bug(7224)}} a causa una potencial vulnerabilitat de seguretat.

+ +

Compatibilitat amb navegadors

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Vegeu també

+ + diff --git a/files/ca/web/javascript/reference/functions/arguments/index.html b/files/ca/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..da5237bdf0 --- /dev/null +++ b/files/ca/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,211 @@ +--- +title: Arguments object +slug: Web/JavaScript/Reference/Functions/arguments +tags: + - Functions + - JavaScript + - NeedsTranslation + - TopicStub + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +
+
{{jsSidebar("Functions")}}
+
+ +

The arguments object is an Array-like object corresponding to the arguments passed to a function.

+ +

Syntax

+ +
arguments
+ +

Description

+ +

The arguments object is a local variable available within all functions. arguments as a property of Function can no longer be used.

+ +

You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as follows:

+ +
arguments[0]
+arguments[1]
+arguments[2]
+
+ +

The arguments can also be set:

+ +
arguments[1] = 'new value';
+ +

The arguments object is not an {{jsxref("Array")}}. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:

+ +
var args = Array.prototype.slice.call(arguments);
+ +
+

Important: You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example). Instead, try constructing a new array by iterating through the arguments object. More information.

+
+ +

If Array generics are available, one can use the following instead:

+ +
var args = Array.slice(arguments);
+ +

The arguments object is available only within a function body. Attempting to access the arguments object outside a function declaration results in an error.

+ +

You can use the arguments object if you call a function with more arguments than it is formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments. You can use arguments.length to determine the number of arguments passed to the function, and then process each argument by using the arguments object. (To determine the number of arguments declared when a function was defined, use the Function.length property.)

+ +

Properties

+ +
+
arguments.callee
+
Reference to the currently executing function.
+
arguments.caller {{ Obsolete_inline() }}
+
Reference to the function that invoked the currently executing function.
+
arguments.length
+
Reference to the number of arguments passed to the function.
+
+ +

Examples

+ +

Defining a function that concatenates several strings

+ +

This example defines a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

+ +
function myConcat(separator) {
+  var args = Array.prototype.slice.call(arguments, 1);
+  return args.join(separator);
+}
+ +

You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.

+ +
// returns "red, orange, blue"
+myConcat(", ", "red", "orange", "blue");
+
+// returns "elephant; giraffe; lion; cheetah"
+myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
+
+// returns "sage. basil. oregano. pepper. parsley"
+myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
+ +

Defining a function that creates HTML lists

+ +

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

+ +
function list(type) {
+  var result = "<" + type + "l><li>";
+  var args = Array.prototype.slice.call(arguments, 1);
+  result += args.join("</li><li>");
+  result += "</li></" + type + "l>"; // end list
+
+  return result;
+}
+ +

You can pass any number of arguments to this function, and it adds each argument as an item to a list of the type indicated. For example:

+ +
var listHTML = list("u", "One", "Two", "Three");
+
+/* listHTML is:
+
+"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
+
+*/
+ +

Rest, default and destructured parameters

+ +

The arguments object can be used in conjunction with rest parameters, default parameters or destructured parameters.

+ +
function foo(...args) {
+  return arguments;
+}
+foo(1, 2, 3); // { "0": 1, "1": 2, "2": 3 }
+
+ +

However, in non-strict functions, a mapped arguments object is only provided if the function does not contain any rest parameters, any default parameters or any destructured parameters. For example, in the following function that uses a default parameter, 10 instead of 100 is returned:

+ +
function bar(a=1) {
+  arguments[0] = 100;
+  return a;
+}
+bar(10); // 10
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES6')}} 
+ +

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/ca/web/javascript/reference/functions/arguments/length/index.html b/files/ca/web/javascript/reference/functions/arguments/length/index.html new file mode 100644 index 0000000000..cf2660b7e4 --- /dev/null +++ b/files/ca/web/javascript/reference/functions/arguments/length/index.html @@ -0,0 +1,117 @@ +--- +title: arguments.length +slug: Web/JavaScript/Reference/Functions/arguments/length +translation_of: Web/JavaScript/Reference/Functions/arguments/length +--- +
{{jsSidebar("Functions")}}
+ +

La propietat arguments.length conté el número d'arguments passats a la funció.

+ +

Sintaxi

+ +
arguments.length
+ +

Descripció

+ +

La propietat arguments.length proporciona el número d'arguments passats a la funció. Aquest pot ser major o menor que el nombre total de paràmetres definits. (Vegeu {{jsxref("Function.length")}}).

+ +

Exemples

+ +

Utilitzar arguments.length

+ +

En aquest exemple definim una funció que pot afegir dos o més nombres.

+ +
function adder(base /*, n2, ... */) {
+  base = Number(base);
+  for (var i = 1; i < arguments.length; i++) {
+    base += Number(arguments[i]);
+  }
+  return base;
+}
+
+ +

Especificacions

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificacióEstatComentaris
{{SpecName('ES1')}}{{Spec2('ES1')}}Definició inicial. Implementat en JavaScript 1.1
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES6')}} 
+ +

Compatibilitat amb navegadors

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vegeu també

+ + diff --git a/files/ca/web/javascript/reference/functions/get/index.html b/files/ca/web/javascript/reference/functions/get/index.html new file mode 100644 index 0000000000..92a9de2965 --- /dev/null +++ b/files/ca/web/javascript/reference/functions/get/index.html @@ -0,0 +1,217 @@ +--- +title: getter +slug: Web/JavaScript/Reference/Functions/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +
{{jsSidebar("Functions")}}
+ +

la sintaxi get lliga la propietat d'un objecte a una funció que es cridarà quan la propietat sigui cercada.

+ +

Sintaxi

+ +
{get prop() { ... } }
+{get [expressió]() { ... } }
+ +

Paràmetres

+ +
+
prop
+
El nom de la propietat que es pretén lligar a la funció donada.
+
expressió
+
A partir d'ECMAScript 6, també es pot utilitzar expressions per a calcular el nom d'una propietat a lligar a la funció donada.
+
+ +

Descripció

+ +

A vegades és desitjable permetre l'accès a una propietat que retorna un valor calculat dinàmicament, o potser es vol reflectir l'estat d'una variable interna sense ésser necessari l'ús de crides explícites a mètodes. En JavaScript, Això es pot aconseguir utilitzant un getter. No és possible tenir simultàniament un lligam a una propietat i que aquesta mateixa propietat contingui un valor, tot i que sí és possible utilitzar un getter i un setter en conjunt per crear un tipus de pseudo-propietat.

+ +

Tingueu en compte el següent quan treballeu amb la sintàxi get:

+ +
+ +
+ +

Un getter pot ser eliminiat utilitzant l'operador delete.

+ +

Exemples

+ +

Definir un getter en nous objectes, en inicialitzadors d'objectes

+ +

Això crearà una pseudo-propietat latest per l'objecte obj, el qual retornarà l'últim ítem de l'array en log.

+ +
var log = ['test'];
+var obj = {
+  get latest () {
+    if (log.length == 0) retorna undefined;
+    return log[log.length - 1]
+  }
+}
+console.log (obj.latest); // Retornarà "test".
+
+ +

Recordeu que intentar assignar un valor a latest no el canviarà.

+ +

Eliminar un getter utilitzanr l'operador delete

+ +

Si voleu eliminar el getter, simplement utilitzeu delete:

+ +
delete obj.latest;
+
+ +

Definir un getter en objectes existents utilitzant la Propietat define

+ +

Per annexar un getter a un objecte existent posteriorment en qualsevol moment, utilitzeu {{jsxref("Object.defineProperty()")}}.

+ +
var o = { a:0 }
+
+Object.defineProperty(o, "b", { get: function () { return this.a + 1; } });
+
+console.log(o.b) // Executa el getter, el qual produeix a + 1 (que és 1)
+ +

Utilitzar un nom de propietat calculat

+ +
+

Nota: Les propietats calculades són una tecnologia experimental, que forma part de la proposta d'ECMAScript 6, i encara no estàn ampliament suportats pels navegadors. Això llençarà un error de sintàxi en entorns que no les suportin.

+
+ +
var expr = "foo";
+
+var obj = {
+  get [expr]() { return "bar"; }
+};
+
+console.log(obj.foo); // "bar"
+ +

 Getters smart / self-overwriting / lazy

+ +

Getters et donen una forma de definir una propietat d'un objecte, però aquests no calculen el valor de la propietat fins que no s'hi ha accedit. getter posposen el cost de calcular el valor fins el moment en que es necessiti el valor, i si no és mai necessari, mai es pagarà el cost.

+ +

Una tècnica d'optimització addiccional per retardar o realitzar de forma lenta el càlcul del valor d'una propietat i guardar-ho per a accedir-hi posteriorment són els getters smart o memoized . El valor és calculat el primer cop que es crida el getter, i és llavors guardat per tal els accessos subsegüents retornin el calor guardat en caché sense recalcular-lo. Això és útil en les situacions següents:

+ + + +

Això vol dir que no haurieu d'utilitzar un getter lazy per una propietat el valor de la qual espereu canviar, ja que el getter no recalcularà el valor.

+ +

En l'exemple següent, l'objecte té un getter com propietat pròpia. Obtenint la propietat, la propietat s'elimina de l'objecte i es reafegeix, però implícitament com a propietat de tipus data aquest cop. Finalment el valor es retorna.

+ +
get notifier() {
+  delete this.notifier;
+  return this.notifier = document.getElementById("bookmarked-notification-anchor");
+},
+ +

Per codi Firefox, vegeu també el mòdul de codi XPCOMUtils.jsm, el qual defineix la funció defineLazyGetter().

+ +

Especificacions

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificacióEstatComentaris
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Definició inicial.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES6')}}Noms de propietats calculats afegits.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilitat amb navegadors

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatChrome(1)}}{{ CompatGeckoDesktop("1.8.1") }}{{ CompatIE(9) }}9.53
Noms de propietats calculats{{CompatChrome(46)}}{{ CompatGeckoDesktop("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.8.1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Noms de propietats calculats47{{CompatNo}}{{ CompatGeckoMobile("34.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Vegeu també

+ + diff --git a/files/ca/web/javascript/reference/functions/index.html b/files/ca/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..1dbb672ef5 --- /dev/null +++ b/files/ca/web/javascript/reference/functions/index.html @@ -0,0 +1,617 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Function + - Functions + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function can return a value.

+ +

In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around just like any other object. Specifically, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

Functions are not the same as procedures. A function always returns a value, but a procedure may or may not return any value.

+ +

To return a specific value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * Declare variable 'mycar';
+  * create and initialize a new Object;
+  * assign reference to it to 'mycar'
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* Pass object reference to the function */
+ myFunc(mycar);
+
+ /*
+  * Logs 'Toyota' as the value of the 'brand' property
+  * of the object, as changed to by the function.
+  */
+ console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details):

+ +
function [name]([param] [, param] [..., param]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements which comprise the body of the function.
+
+ +

The generator function declaration (function* statement)

+ +
+

Note: Generator function are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

There is a special syntax for declaration generator functions (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +
+

Note: Generator function are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param] [, param] [..., param]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements which comprise the body of the function.
+
+ +

The arrow function expression (=>)

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param] [, param]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of that function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for 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.
+
+ +

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

+ +

The GeneratorFunction constructor

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for 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.
+
+ +

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

+ +

Function parameters

+ +
+

Note: Default and rest parameters are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +
+

Note: Method definitions are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Starting with ECMAScript 6, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Function constructor vs. function declaration vs. function expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
function multiply(x, y) {
+   return x * y;
+}
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x == 0) {            // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y == 10) {     // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Conditionally defining a function

+ +

Functions can be conditionally defined using either //function statements// (an allowed extension to the ECMA-262 Edition 3 standard) or the Function constructor. Please note that such function statements are no longer allowed in ES5 strict. Additionally, this feature does not work consistently cross-browser, so you should not rely on it.

+ +

In the following script, the zero function is never defined and cannot be invoked, because 'if (0)' evaluates its condition to false:

+ +
if (0) {
+   function zero() {
+      document.writeln("This is zero.");
+   }
+}
+
+ +

If the script is changed so that the condition becomes 'if (1)', function zero is defined.

+ +

Note: Although this kind of function looks like a function declaration, it is actually an expression (or statement), since it is nested within another statement. See differences between function declarations and function expressions.

+ +

Note: Some JavaScript engines, not including SpiderMonkey, incorrectly treat any function expression with a name as a function definition. This would lead to zero being defined, even with the always-false if condition. A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:

+ +
if (0) {
+   var zero = function() {
+      document.writeln("This is zero.");
+   }
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is peformed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' == typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters
{{SpecName('ES6', '#', 'function*')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ES6', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES6')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator function39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow function{{CompatNo}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator function{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow function{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/ca/web/javascript/reference/functions/parameters_rest/index.html b/files/ca/web/javascript/reference/functions/parameters_rest/index.html new file mode 100644 index 0000000000..68fc5f0bba --- /dev/null +++ b/files/ca/web/javascript/reference/functions/parameters_rest/index.html @@ -0,0 +1,156 @@ +--- +title: Paràmetres rest +slug: Web/JavaScript/Reference/Functions/parameters_rest +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +
{{jsSidebar("Functions")}}
+ +

El paràmetre rest ens permet  representar un nombre indefinit d'arguments en forma d 'array.

+ +

Syntax

+ +
function f(a, b, ...theArgs) {
+  // ...
+}
+
+ +

Descripció

+ +

Si l'últim argument d'una funció, està prefixat amb l'operador ..., aquest esdevé un array el qual té com a elements des de 0 (inclòs) fins a theArgs.length (no inclòs) els arguments passats a la funció.

+ +

A l'exemple de sobre, theArgs aglutina el tercer argument de la funció, ja que el primer està mapejat a a  i el segon està mapejat a b , i tota la resta d'arguments consecutius. 

+ +

Diferència entre els paràmetres rest i l'objecte arguments

+ +

Existeixen tres diferències principals entre els  paràmetres rest i l'objecte arguments

+ + + +

Des d' arguments fins a un array

+ +

El paràmetre rest ha estat introduit per tal de reduir la quantitat de codi utilitzat que es introduit per els arguments

+ +
// Anteriorment a l' existència del paràmetre rest el s' utilitzava seguent codi
+function f(a, b) {
+  var args = Array.prototype.slice.call(arguments, f.length);
+
+  // …
+}
+
+// equivalent a
+
+function f(a, b, ...args) {
+
+}
+
+ +

Desestructurant paràmetres rest

+ +

Els paràmetres rest es poden desestructurar, que vol dir que els valors que contenen es poden desenpaquetar en variables diferents i separades. Vegeu Destructuring assignment.

+ +
function f(...[a, b, c]) {
+  return a + b + c;
+}
+
+f(1)          // NaN (bi c són undefined)
+f(1, 2, 3)    // 6
+f(1, 2, 3, 4) // 6 (el quart paràmetre no està desetructurat)
+ +

Exemples

+ +

Com que theArgs és un array, la propietat length en retorna el recompte:

+ +
function fun1(...theArgs) {
+  console.log(theArgs.length);
+}
+
+fun1();  // 0
+fun1(5); // 1
+fun1(5, 6, 7); // 3
+
+ +

En el seguent exemple el paràmetre rest s' utilitza per aglutinar tots els paràmetres passats a la funcció després del primer en un array. Després cadascun d' ells és multiplicat per el primer paràmetre passat a la funció i es retorna l' array.

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(function(element) {
+    return multiplier * element;
+  });
+}
+
+var arr = multiply(2, 1, 2, 3);
+console.log(arr); // [2, 4, 6]
+
+ +

El seguent exemple mostra com els mètodes d' Array es poden utilitzar am paràmetres rest, però no amb l' objecte arguments :

+ +
function sortRestArgs(...theArgs) {
+  var sortedArgs = theArgs.sort();
+  return sortedArgs;
+}
+
+console.log(sortRestArgs(5, 3, 7, 1)); // mostra 1, 3, 5, 7
+
+function sortArguments() {
+  var sortedArgs = arguments.sort();
+  return sortedArgs; // aquesta línia mai s' executarà
+}
+
+// genera el TypeError: arguments.sort no és una funció
+console.log(sortArguments(5, 3, 7, 1));
+
+ +

Per tal de poder usar els mètodes d' Array amb l' objecte arguments , aquest s' ha de convertir primer en un array.

+ +
function sortArguments() {
+  var args = Array.prototype.slice.call(arguments);
+  var sortedArgs = args.sort();
+  return sortedArgs;
+}
+console.log(sortArguments(5, 3, 7, 1)); // shows 1, 3, 5, 7
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES6')}}Initial definition
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.functions.rest_parameters")}}

+
+ +

See also

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