From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../functions/funkcje_strzalkowe/index.html | 355 +++++++++++ .../javascript/reference/functions/get/index.html | 216 +++++++ .../web/javascript/reference/functions/index.html | 657 +++++++++++++++++++++ .../parametry_domy\305\233lne/index.html" | 225 +++++++ .../javascript/reference/functions/set/index.html | 146 +++++ 5 files changed, 1599 insertions(+) create mode 100644 files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html create mode 100644 files/pl/web/javascript/reference/functions/get/index.html create mode 100644 files/pl/web/javascript/reference/functions/index.html create mode 100644 "files/pl/web/javascript/reference/functions/parametry_domy\305\233lne/index.html" create mode 100644 files/pl/web/javascript/reference/functions/set/index.html (limited to 'files/pl/web/javascript/reference/functions') diff --git a/files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html b/files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html new file mode 100644 index 0000000000..d1b9d6010f --- /dev/null +++ b/files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html @@ -0,0 +1,355 @@ +--- +title: Funkcje strzałkowe +slug: Web/JavaScript/Reference/Functions/Funkcje_strzalkowe +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

Funkcja strzałkowa ma krótszą składnię niż zwykłe wyrażenie funkcji oraz nie posiada własnego this, argumentów, super, tudzież właściwości new.target. Taki sposób wyrażenia funkcji najlepiej wykorzystać przy tworzeniu funkcji bez metod, ponadto nie mogą zostać one użyte jako konstruktory.

+ +

Składnia

+ +

Składnia podstawowa

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// inaczej mówiąc: (param1, param2, …, paramN) => { return expression; }
+
+// Nawiasy są opcjonalne jeżeli występuje wyłącznie jedna nazwa parametru:
+(singleParam) => { statements }
+singleParam => { statements }
+singleParam => expression
+
+
+// Lista parametrów dla funkcji bez parametrów powinna być zapisana przy użyciu pustego nawiasu.
+() => { statements }
+
+ +

Zaawansowana składnia

+ +
// Otoczenie ciała funkcji nawiasami pozwoli zwrócić tzw. object literal expression:
+params => ({foo: bar})
+
+// Parametry Rest (Rest parameters) i domyślne (default parameters) są wspierane
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
+
+// Destrukturyzacja (Destructuring) w ramach listy parametrów jest również wspierana
+let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f();
+// 6
+
+ +

Opis

+ +

Zobacz również "ES6 In Depth: Arrow functions" na hacks.mozilla.org.

+ +

Dwa czynniki, które wpłynęły na wprowadzenie funkcji strzałkowych: krótszy zapis funkcji i brak wiązania this.

+ +

Krótsze funkcje

+ +
var materials = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+materials.map(function(material) {
+  return material.length;
+}); // [8, 6, 7, 9]
+
+materials.map((material) => {
+  return material.length;
+}); // [8, 6, 7, 9]
+
+materials.map(material => material.length); // [8, 6, 7, 9]
+
+materials.map(({ length }) => length); // [8, 6, 7, 9]
+
+ +

Brak oddzielnego this

+ +

Przed wprowadzeniem funkcji strzałkowych każda nowa funkcja deniniowała swoją własną wartość this (nowy obiekt w przypadku konstruktora, undefined w wywołaniach funkcji strict mode, obiekt bazowy jeśli funkcja jest wywoływana jako "metoda obiektowa", itp.). Okazało się to niekorzystne przy obiektowym stylu programowania.

+ +
function Person() {
+  // Konstruktor Person() definiuje `this` jako instancję samego siebie.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // Bez trybu non-strict, funkcja growUp() definuje `this`
+    // jako obiekt globalny, który jest inny od `this`
+    // zdefiniowanego przez konstruktor Person().
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

W ECMAScript 3/5, problem z this można było rozwiązać przez przydzielenie wartości this do zmiennej, która wygląda bardzo podobnie.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `that` variable of which
+    // the value is the expected object.
+    that.age++;
+  }, 1000);
+}
+ +

Można było również stworzyć funkcję bound, co pozwoliło nadać wstępnie przypisaną wartość this do powiązanej funkcji docelowej (funkcja growUp() w przykładzie powyżej).

+ +

Funkcja strzałkowa nie posiada własnego this; używana jest wartość this kontekstu wykonania. W związku z tym, w poniższym kodzie, this użyty w funkcji, który jest przekazywany do setInterval, ma taką samą wartość jak this w funkcji otaczającej:

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // własność |this| właściwie odnosi się do obiektu Person()
+  }, 1000);
+}
+
+var p = new Person();
+ +

Relation with strict mode

+ +

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // or the global object
+ +

All other strict mode rules apply normally.

+ +

Invoked through call or apply

+ +

Since arrow functions do not have their own this, the methods call() or apply() can only pass in parameters. thisArg is ignored.

+ +
var adder = {
+  base: 1,
+
+  add: function(a) {
+    var f = v => v + this.base;
+    return f(a);
+  },
+
+  addThruCall: function(a) {
+    var f = v => v + this.base;
+    var b = {
+      base: 2
+    };
+
+    return f.call(b, a);
+  }
+};
+
+console.log(adder.add(1));         // This would log to 2
+console.log(adder.addThruCall(1)); // This would log to 2 still
+ +

No binding of arguments

+ +

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the the arguments of the enclosing scope:

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f(10);
+}
+
+foo(1); // 2
+ +

In most cases, using rest parameters is a good alternative to using an arguments object.

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(10);
+}
+
+foo(1); // 11
+ +

Arrow functions used as methods

+ +

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

+ +
'use strict';
+var obj = {
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log(this.i, this);
+  }
+}
+obj.b(); // prints undefined, Window {...} (or the global object)
+obj.c(); // prints 10, Object {...}
+ +

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

+ +
'use strict';
+var obj = {
+  a: 10
+};
+
+Object.defineProperty(obj, 'b', {
+  get: () => {
+    console.log(this.a, typeof this.a, this);
+    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+
+ +

Use of the new operator

+ +

Arrow functions cannot be used as constructors and will throw an error when used with new.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

Use of prototype property

+ +

Arrow functions do not have a prototype property.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+
+ +

Use of the yield keyword

+ +

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

+ +

Function body

+ +

Arrow functions can have either a "concise body" or the usual "block body".

+ +

In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.

+ +
var func = x => x * x;
+// concise body syntax, implied "return"
+
+var func = (x, y) => { return x + y; };
+// with block body, explicit "return" needed
+
+ +

Returning object literals

+ +

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

+ +
var func = () => { foo: 1 };
+// Calling func() returns undefined!
+
+var func = () => { foo: function() {} };
+// SyntaxError: function statement requires a name
+ +

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

+ +

Remember to wrap the object literal in parentheses.

+ +
var func = () => ({foo: 1});
+ +

Line breaks

+ +

An arrow function cannot contain a line break between its parameters and its arrow.

+ +
var func = ()
+           => 1;
+// SyntaxError: expected expression, got '=>'
+ +

Parsing order

+ +

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

More examples

+ +
// An empty arrow function returns undefined
+let empty = () => {};
+
+(() => 'foobar')();
+// Returns "foobar"
+// (this is an Immediately Invoked Function Expression
+// see 'IIFE' in glossary)
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Easy array filtering, mapping, ...
+
+var arr = [5, 6, 13, 0, 1, 18, 23];
+
+var sum = arr.reduce((a, b) => a + b);
+// 66
+
+var even = arr.filter(v => v % 2 == 0);
+// [6, 0, 18]
+
+var double = arr.map(v => v * 2);
+// [10, 12, 26, 0, 2, 36, 46]
+
+// More concise promise chains
+promise.then(a => {
+  // ...
+}).then(b => {
+  // ...
+});
+
+// Parameterless arrow functions that are visually easier to parse
+setTimeout( () => {
+  console.log('I happen sooner');
+  setTimeout( () => {
+    // deeper code
+    console.log('I happen later');
+  }, 1);
+}, 1);
+
+ +

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/functions/get/index.html b/files/pl/web/javascript/reference/functions/get/index.html new file mode 100644 index 0000000000..0c4cf664dc --- /dev/null +++ b/files/pl/web/javascript/reference/functions/get/index.html @@ -0,0 +1,216 @@ +--- +title: getter +slug: Web/JavaScript/Reference/Functions/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +
{{jsSidebar("Functions")}}
+ +
Składnia get łączy właściwość obiektu z funkcją, która będzie wykonywana za każdym razem, kiedy ta właściwość jest wywoływana.
+ +
+ +

Składnia

+ +
{get prop() { ... } }
+{get [expression]() { ... } }
+ +

Parametry

+ +
+
prop
+
Nazwa właściwości, która łączy ją z okresloną funkcją.
+
expression
+
Począwszy od ECMAScript 2015, można również użyć wyrażeń w celu połaczenia funkcji z nazwą właściwości, która jest obliczana.
+
+ +

Opis

+ +

Czasami pożądane jest aby umożliwić dostęp do właściwości, która zwraca wartość obliczaną dynamicznie lub potrzeba odzwierciedlić stan jakiejś wewnętrznej zmiennej bez potrzeby użycia wyraźnego wywołania metody. W języku JavaScript może to być osiągnięte dzięki użyciu gettera. Nie jest możliwe jednocześnie mieć getter połączony z właściwością i mieć tą właściwość (o takiej samej nazwie jak getter), która faktycznie trzyma wartość. Jednakże jest możliwe aby używać połączenia gettera i settera, żeby utworzyć rodzaj pseudo-właściwości.

+ +

Zauważ, że gdy pracujemy ze składnią get to:

+ +
+ +
+ +

Getter może być usunięty poprzez operator delete.

+ +

Przykłady

+ +

Definiowanie gettera na nowym obiekcie w inicjalizatorze obiektu.

+ +

To stworzy pseudowłaściwość latest dla obiektu obj, która zwróci ostatnio zalogowany element w tablicy log.

+ +
var obj = {
+  log: ['test'],
+  get latest() {
+    if (this.log.length == 0) return undefined;
+    return this.log[this.log.length - 1];
+  }
+}
+console.log(obj.latest); // Zwróci "test".
+
+ +

Zauważ, że usiłowanie przypisania wartości do latest nie zmieni jej.

+ +

Usuwanie gettera używając operatora delete

+ +

Jeśli chcesz usunąć getter, wystarczy użyć delete :

+ +
delete obj.latest;
+
+ +

Definiowanie gettera na istniejącym obiekcie uzywając defineProperty

+ +

Aby dołączyć getter do istniejącego obiektu, można w każdej chwili użyć:
+ {{jsxref("Object.defineProperty()")}}.

+ +
var o = {a: 0};
+
+Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } });
+
+console.log(o.b) // Uruchamia getter, który otrzymuje yields a + 1 (which is 1)
+ +

Używanie obliczanych wartości dla właściwości.

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

Bystre / samo-nadpisujące / leniwe gettery

+ +

Gettery dają ci możliwośc zdefiniowania właściwości obiektu, ale nie obliczają wartości właściwości dopóki nie jest ona dostępna. Getter odracza koszt obliczania wartości dopóki ta wartość jest potrzebna, a jeśli nigdy nie jest potrzebna, nie ponosi się tego kosztu.

+ +

Dodatkową techniką optymalizacyjna aby uleniwić lub opóźnić obliczanie wartości dla właściwości jak i przechować ją na później są bystre (smart) lub zmemoizowane gettery. Wartość jest obliczana gdy getter jest wywoływany za pierwszym razem, a potem jest przechowywana więc kolejne dostępy zwracają zbuforowaną wartość bez jej ponownego obliczania. Jest to użyteczne w następujących sytuacjach:

+ + + +

To oznacza, że nie powinno się używać leniwych getterów dla właściwości, której wartość może ulec zmianie, ponieważ taki getter nie oblicza właściwości ponownie.

+ +

W następującym przykładzie obiekt posiada getter jako swoją właściwość. Otrzymując tą właściwość, jest ona usuwana z obiektu i ponownie dodawana, ale niejawnie jako właściwość z przypisanymi danymi. W ostatecznym rozrachunku zwracana jest wartość.

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

Na potrzeby kodu Firefoxa, zobacz również moduł z kodem XPCOMUtils.jsm, który okresla funkcje defineLazyGetter().

+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjeStatusComment
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES2015', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES2015')}}Added computed property names.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}}
+ +

Zgodność z przeglądarkami

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{ CompatGeckoDesktop("1.8.1") }}{{ CompatIE(9) }}9.53
Computed property names{{CompatChrome(46)}}{{ CompatGeckoDesktop("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.8.1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Computed property names47{{CompatNo}}{{ CompatGeckoMobile("34.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Zobacz również

+ + diff --git a/files/pl/web/javascript/reference/functions/index.html b/files/pl/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..e7935d3318 --- /dev/null +++ b/files/pl/web/javascript/reference/functions/index.html @@ -0,0 +1,657 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +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 will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, 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.

+ +

To return a 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 {{jsxref("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). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
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 comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both example do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When function are used only once, a common pattern is an IIFE (Immediately Invokable Function Expressions).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expression that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (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)

+ +

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 comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

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 the 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 parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

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

+ +

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

+ +

Starting with ECMAScript 2015, 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:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

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

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (0) {
+   zero = function() {
+      console.log("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 performed 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('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatChrome(45.0)}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatOpera(32)}}10
Block-level functions{{CompatUnknown}}{{CompatGeckoDesktop("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git "a/files/pl/web/javascript/reference/functions/parametry_domy\305\233lne/index.html" "b/files/pl/web/javascript/reference/functions/parametry_domy\305\233lne/index.html" new file mode 100644 index 0000000000..b192456adf --- /dev/null +++ "b/files/pl/web/javascript/reference/functions/parametry_domy\305\233lne/index.html" @@ -0,0 +1,225 @@ +--- +title: Parametry domyślne +slug: Web/JavaScript/Reference/Functions/Parametry_domyślne +tags: + - ECMAScript2015 + - Funkcje + - JavaScript +translation_of: Web/JavaScript/Reference/Functions/Default_parameters +--- +
{{jsSidebar("Functions")}}
+ +

Domyślne parametry funkcji pozwalają na inicjalizację nazwanych parametrów wartościami domyślnymi tam, gdzie nie została podana żadna wartość lub jako wartość podano undefined.

+ +
{{EmbedInteractiveExample("pages/js/functions-default.html")}}
+ + + +

Składnia

+ +
function [nazwa]([parametr1[ = domyślnaWartość1 ][, ..., parametrN[ = domyślnaWartośćN ]]]) {
+   ciało funkcji
+}
+
+ +

Opis

+ +

W języku JavaScript domyślną wartością parametrów funkcji jest {{jsxref("undefined")}}. Często jednak dobrze jest ustawić inną wartość domyślną – wówczas parametry domyślne okazują się pomocne.

+ +

W przeszłości, ogólną strategią na ustawianie domyślnych wartości było sprawdzanie parametrów w ciele funkcji – w sytuacji, w których były one równe undefined, przypisywano im konkretne wartości.

+ +

W następującym przykładzie, jeśli żadna wartość nie jest podana jako b, kiedy wywoływana jest funkcja pomnóż, wartość b powinna być równa undefined – wówczas funkcja powinna zwrócić NaN jako wynik operacji a * b.

+ +
function pomnóż(a, b) {
+  return a * b;
+}
+
+pomnóż(5, 2); // 10
+pomnóż(5);    // NaN !
+
+ +

Aby się przed tym uchronić, należy użyć czegoś takiego, jak w drugiej linijce, gdzie wartość b jest ustawiana na 1, jeśli funkcja pomnóż jest wywoływana tylko z jednym argumentem.

+ +
function pomnóż(a, b) {
+  b = (typeof b !== 'undefined') ?  b : 1;
+  return a * b;
+}
+
+pomnóż(5, 2); // 10
+pomnóż(5);    // 5
+
+ +

Dzięki parametrom domyślnym w ES2015, tego rodzaju sprawdzanie wartości parametrów w ciele funkcji nie jest już konieczne. Można teraz przypisać 1 jako domyślną wartość w nagłówku funkcji:

+ +
function pomnóż(a, b = 1) {
+  return a * b;
+}
+
+pomnóż(5, 2); // 10
+pomnóż(5);    // 5
+
+ +

Przykłady

+ +

Przekazywanie undefined kontra inne puste wartości

+ +

W drugim wywołaniu funkcji w tym przykłądzie, nawet jeśli jako pierwszy argument wprost podany undefined (jednak nie null lub inne puste wartości), wartością argumentu num dalej będzie wartość domyślna.

+ +
function test(num = 1) {
+  console.log(typeof num);
+}
+
+test();          // 'number' (num jest ustawiany na 1)
+test(undefined); // 'number' (num również jest ustawiany na 1)
+
+// test z innymi "pustymi" wartościami:
+test('');        // 'string' (num jest ustawiany na '')
+test(null);      // 'object' (num jest ustawiany na null)
+
+ +

Ewaluacja w czasie wykonania

+ +

Domyślne argumenty są przypisywane w czasie wykonania, a więc w odróżnieniu od np. Pythona, nowy obiekt jest tworzony przy każdym wywołaniu funkcji.

+ +
function append(wartość, tablica = []) {
+  array.push(wartość);
+  return tablica;
+}
+
+append(1); //[1]
+append(2); //[2], nie [1, 2]
+
+ +

Dotyczy to również funkcji i zmiennych:

+ +
function callSomething(thing = something()) {
+ return thing;
+}
+
+let numberOfTimesCalled = 0;
+function something() {
+  numberOfTimesCalled += 1;
+  return numberOfTimesCalled;
+}
+
+callSomething(); // 1
+callSomething(); // 2
+ +

Domyślne parametry są dostępne dla późniejszych domyślnych parametrów

+ +

Parametry zdefiniowane wcześniej (bardziej na lewo na liście parametrów), są dostępne dla domyślnych parametrów definiowanych później:

+ +
function pozdrów(imię, pozdrowienie, wiadomość = pozdrowienie + ' ' + imię) {
+    return [imię, pozdrowienie, wiadomość];
+}
+
+pozdrów('Dawid', 'Cześć');  // ["Dawid", "Cześć", "Cześć Dawid"]
+pozdrów('Dawid', 'Cześć', 'Wszystkiego najlepszego!');  // ["Dawid", "Cześć", "Wszystkiego najlepszego!"]
+
+ +

Ta funkcjonalność może być przybliżona w ten sposób, pokazujący, jak wiele przypadków brzegowych może być obsłużonych:

+ +
function go() {
+  return ':P';
+}
+
+function withDefaults(a, b = 5, c = b, d = go(), e = this,
+                      f = arguments, g = this.value) {
+  return [a, b, c, d, e, f, g];
+}
+
+function withoutDefaults(a, b, c, d, e, f, g) {
+  switch (arguments.length) {
+    case 0:
+      a;
+    case 1:
+      b = 5;
+    case 2:
+      c = b;
+    case 3:
+      d = go();
+    case 4:
+      e = this;
+    case 5:
+      f = arguments;
+    case 6:
+      g = this.value;
+    default:
+  }
+  return [a, b, c, d, e, f, g];
+}
+
+withDefaults.call({value: '=^_^='});
+// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
+
+withoutDefaults.call({value: '=^_^='});
+// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
+
+ +

Funkcje definiowane w ciele funkcji

+ +

Wprowadzone w Gecko 33 {{geckoRelease(33)}}. Funkcje deklarowane w ciele funkcji nie mogą być używane jako wartości domyślne w tej samej funkcji. Przy takiej próbie, wyrzucany jest jest {{jsxref("ReferenceError")}}. Parametr domyślny zawsze wykonywany jest jako pierwszy, a więc deklaracje w ciele funkcji są ewaluowane później.

+ +
// Nie działa! Wyrzuca ReferenceError.
+function f(a = go()) {
+  function go() { return ':P'; }
+}
+
+ +

Parametry bez wartości domyślnych po parametrach domyślnych

+ +

Przed Gecko 26 {{geckoRelease(26)}}, poniższy kod zwracał {{jsxref("SyntaxError")}}. Zostało to naprawione w {{bug(777060)}}. Wartości parametrów dalej są ustawiane w kolejności od lewej do prawej, nadpisując domyślne parametry, nawet jeśli występują potem parametry bez wartości domyślnych.

+ +
function f(x = 1, y) {
+  return [x, y];
+}
+
+f(); // [1, undefined]
+f(2); // [2, undefined]
+
+ +

Parametr destrukturyzowany z przypisaniem domyślnej wartości

+ +

Możesz też użyć przypisania domyślnej wartości z notacją parametru destruktyryzowanego:

+ +
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
+  return x + y + z;
+}
+
+f(); // 6
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}}
+ +

Wsparcie przeglądarek

+ +
+ + +

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

+
+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/functions/set/index.html b/files/pl/web/javascript/reference/functions/set/index.html new file mode 100644 index 0000000000..d3eb6ad31d --- /dev/null +++ b/files/pl/web/javascript/reference/functions/set/index.html @@ -0,0 +1,146 @@ +--- +title: setter +slug: Web/JavaScript/Reference/Functions/set +translation_of: Web/JavaScript/Reference/Functions/set +--- +
{{jsSidebar("Functions")}}
+ +

Składnia set wiąże właściwość obiektu z funkcją, która zostanie wywołana przy próbie przypisania wartości danej właściwości.

+ +
{{EmbedInteractiveExample("pages/js/functions-setter.html")}}
+ + + +

Składnia

+ +
{set prop(val) { . . . }}
+{set [expression](val) { . . . }}
+ +

Parametry

+ +
+
prop
+
Nazwa właściwości wiązanej z określoną funkcją.
+
+ +
+
val
+
Zmienna przechowująca wartość przekazaną do przypisania do właściwości prop.
+
expression
+
Począwszy od ECMAScript 2015, można również użyć wyrażeń w celu połaczenia funkcji z nazwą właściwości, która jest obliczana.
+
+ +

Description

+ +

Setter może być użyty do wywołania określonej funkcji przy każdej próbie przypisania wartości do danej właściwości. Settery są najczęściej używane razem z getterami żeby utworzyć rodzaj pseudo-właściwości. Nie ma możliwości jednoczesnego używania settera oraz faktycznej wartości przypisanej do danej właściwości.

+ +

Uwagi do składni set:

+ +
+ +
+ +

Setter może być usunięty przy użyciu operatora delete.

+ +

Przykłady

+ +

Definicja settera w nowym obiekcie podczas inicjalizacji

+ +

Poniższa składnia definiuje pseudo-właściwość current obiektu language, która podczas przypisania wartości aktualizuje tablicę log o tą wartość:

+ +
var language = {
+  set current(name) {
+    this.log.push(name);
+  },
+  log: []
+}
+
+language.current = 'EN';
+console.log(language.log); // ['EN']
+
+language.current = 'FA';
+console.log(language.log); // ['EN', 'FA']
+
+ +

Zwróć uwagę, że właściwość current nie jest zdefiniowana i próby odczytu zwrócą undefined.

+ +

Usuwanie settera przy użyciu operatora delete

+ +

Setter może zostać usunięty przy użyciu delete:

+ +
delete o.current;
+
+ +

Definicja settera dla istniejącego obiektu przy użyciu defineProperty

+ +

Aby zdefiniować setter dla istniejącego obiektu po jego uprzednim utworzeniu użyj {{jsxref("Object.defineProperty()")}}.

+ +
var o = {a: 0};
+
+Object.defineProperty(o, 'b', { set: function(x) { this.a = x / 2; } });
+
+o.b = 10; // Uruchamia setter, który przypisuje 10 / 2 (5) do właściwości 'a'
+console.log(o.a) // 5
+ +

Używanie wyrażenia do obliczenia nazwy settera

+ +
var expr = 'foo';
+
+var obj = {
+  baz: 'bar',
+  set [expr](v) { this.baz = v; }
+};
+
+console.log(obj.baz); // "bar"
+obj.foo = 'baz';      // uruchom setter
+console.log(obj.baz); // "baz"
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES6')}}Added computed property names.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}} 
+ +

Zgodność z przeglądarkami

+ + + +

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

+ +

Zobacz również

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