From de5c456ebded0e038adbf23db34cc290c8829180 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:49:24 +0100 Subject: unslug pl: move --- .../global_objects/function/apply/index.html | 289 ++++++++++++++++++ .../global_objects/function/arguments/index.html | 41 +++ .../global_objects/function/bind/index.html | 332 +++++++++++++++++++++ .../global_objects/function/caller/index.html | 69 +++++ .../global_objects/function/displayname/index.html | 119 ++++++++ .../reference/global_objects/function/index.html | 237 +++++++++++++++ .../global_objects/function/length/index.html | 42 +++ .../global_objects/function/tostring/index.html | 56 ++++ 8 files changed, 1185 insertions(+) create mode 100644 files/pl/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/caller/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/displayname/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/pl/web/javascript/reference/global_objects/function/tostring/index.html (limited to 'files/pl/web/javascript/reference/global_objects/function') diff --git a/files/pl/web/javascript/reference/global_objects/function/apply/index.html b/files/pl/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..411b47423a --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,289 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Referencje/Obiekty/Function/apply +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
{{JSRef}}
+ +

Metoda apply() wywołuje daną funkcję podstawiając daną wartość this i argumenty przedstawione w postaci tablicy (lub obiektu tablicopodobnego (array-like object)).

+ +
+

Notka: Składnia tej funkcji jest niemal identyczna do {{jsxref("Function.call", "call()")}}, podstawową różnicą jest to, iż call() przyjmuje listę argumentów, podczas gdy apply() akceptuje pojedynczą tablicę argumentów.

+
+ +

Składnia

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

Parametry

+ +
+
thisArg
+
Optional. The value of this provided for the call to func. Note that this may not be the actual value seen by the method: if the method is a function in {{jsxref("Strict_mode", "non-strict mode", "", 1)}} code, {{jsxref("null")}} and {{jsxref("undefined")}} will be replaced with the global object, and primitive values will be boxed.
+
argsArray
+
Optional. An array-like object, specifying the arguments with which fun should be called, or {{jsxref("null")}} or {{jsxref("undefined")}} if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for {{anch("Browser_compatibility", "browser compatibility")}} information.
+
+ +

Zwracana wartość

+ +

Wynik wywoływanej funkcji z określoną wartością this i argumentami.

+ +

Opis

+ +

Można przypisać inny obiekt this podczas wywoływania istniejącej funkcji. this odnosi się do bieżącego obiektu, obiektu wywołującego. Z apply można napisać metodę raz, a następnie dziedziczyć w innym obiekcie, bez konieczności przepisywania metody dla nowego obiektu.

+ +

apply jest bardzo podobne do {{jsxref("Function.call", "call()")}}, z wyjątkiem typu danych argumentów, które wspiera. Można używać tablicy argumentów zamiast zestawu argumentów (parametrów). Z metodą apply, możesz używać tablic w sensie dosłownym, na przykład func.apply(this, ['eat', 'bananas']), lub obiektów typu {{jsxref("Array")}}, na przykład, func.apply(this, new Array('eat', 'bananas')).

+ +

Można używać również {{jsxref("Funkcje/arguments", "arguments")}} dla parametru argsArray. arguments jest zmienną lokalną dostępną wewnątrz każdej funkcji. Można to zastosować do wszystkich nieokreślonych argumentów wywoływanego obiektu. Tak więc nie trzeba znać argumentów wywoływanego obiektu przy użyciu metody apply Możesz użyć arguments, aby przekazać wszystkie argumenty do wywoływanego obiektu. Wywołany obiekt jest odpowiedzialny za obsługę otrzymanych argumentów.

+ +

Od ECMAScript 5th Edition możliwe jest również używanie wszelkiego rodzaju obiektów „tablicopodobnych” (array-like), co w praktyce oznacza, że obiekt taki musi mieć własność length i całkowite własności (indeksy) w zakresie (0..length-1). Przykładowo możesz użyć {{domxref("NodeList")}} lub własnego oiektu jak np. { 'length': 2, '0': 'eat', '1': 'bananas' }.

+ +
+

Większość przeglądarek, w tym Chrome 14 i Internet Explorer 9, w dalszym ciągu nie akceptuje obiektów tablicopodobnych i będzie wyrzucać wyjątek.

+
+ +

Przykłady

+ +

Użycie apply do dodania tablicy do innej tablicy

+ +

Możemy użyć metody push do dodania elementu do tablicy. I, jako że push przyjmuje zmienną liczbę argumentów, możemy również dodać wiele elementów naraz – ale jeśli faktycznie przekażemy tablicę do funkcji push, wówczas rzeczywiście doda ona tablicę jako pojedynczy element, zamiast dodać jej elementy, więc skończymy z tablicą wewnątrz tablicy. Co jeśli to nie jest to, co chcieliśmy osiągnąć? concat ma zachowanie takie, jakiego oczekiwalibyśmy w tym przypadku, jednak funkcja ta nie dodaje w rzeczywistości tablicy do istniejącej tablicy, ale tworzy i zwraca nową. Ale chcieliśmy zmodyfikować naszą istniejącą tablicę… Więc co teraz? Napisać pętlę? No chyba nie?

+ +

apply przychodzi na ratunek!

+ +
var array = ['a', 'b'];
+var elements = [0, 1, 2];
+array.push.apply(array, elements);
+console.info(array); // ["a", "b", 0, 1, 2]
+
+ +

 

+ +

Using apply and built-in functions

+ +

 

+ +

Clever usage of apply allows you to use built-ins functions for some tasks, that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min, to find out the maximum/minimum value in an array.

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

But beware: in using apply this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.

+ +

If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:

+ +
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]);
+
+ +

 

+ +

Using apply to chain constructors

+ +

 

+ +

You can use apply to chain {{jsxref("Operators/new", "constructors", "", 1)}} for an object, similar to Java. In the following example we will create a global {{jsxref("Function")}} method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list.

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

Note: The Object.create() method used above is relatively new. For alternative methods, please consider one of the following approaches:

+ +

Using {{jsxref("Object/__proto__", "Object.__proto__")}}:

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

Using closures:

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

Using the {{jsxref("Function")}} constructor:

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

Example usage:

+ +
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: This non-native Function.construct method will not work with some native constructors; like {{jsxref("Date")}}, for example. In these cases you have to use the {{jsxref("Function.prototype.bind")}} method. For example, imagine having an array like the following, to be used with {{jsxref("Global_Objects/Date", "Date")}} constructor: [2012, 11, 4]; in this case you have to write something like: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))(). This is not the best way to do things, and probably not to be used in any production environment.

+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented 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')}} 
+ +

Zgodność z przeglądarkami

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Zobacz również

+ + diff --git a/files/pl/web/javascript/reference/global_objects/function/arguments/index.html b/files/pl/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..abbb63eef4 --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,41 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Referencje/Obiekty/Function/arguments +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +

{{JSRef}}{{ Deprecated_header() }}

+ +

Podsumowanie

+ +

Obiekt tablicopodobny odpowiadający argumentom przekazywanym funkcji.

+ +

Opis

+ +

Należy użyć obiektu arguments dostępnego wewnątrz funkcji zamiast Function.arguments.

+ +

W przypadku rekurencji, tzn. jeśli funkcja f pojawia się kilkakrotnie na stosie wywołania, wartość of f.arguments reprezentuje argumenty odpowiadające ostatniemu wywołaniu funkcji.

+ +

Przykład

+ +
function f(n) { g(n-1) }
+
+function g(n) {
+  console.log("przed: " + g.arguments[0]);
+  if(n>0) { f(n); }
+  console.log("po: " + g.arguments[0]);
+}
+f(2);
+
+ +

wyświetli:

+ +
przed: 1
+przed: 0
+po: 0
+po: 1
+
diff --git a/files/pl/web/javascript/reference/global_objects/function/bind/index.html b/files/pl/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..028db6b6d4 --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,332 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Referencje/Obiekty/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+Metoda bind() tworzy nową funkcję, której wywołanie powoduje ustawienie this na podaną wartość, z podaną sekwencją argumentów poprzedzającą dowolną podaną podczas wywołania nowej funkcji.
+ +
{{EmbedInteractiveExample („pages / js / function-bind.html”, „taller”)}}
+Źródło tego interaktywnego przykładu jest przechowywane w repozytorium GitHub. Jeśli chcesz przyczynić się do projektu interaktywnych przykładów, sklonuj https://github.com/mdn/interactive-examples i wyślij nam prośbę o pobranie.
+ +

Syntax

+ +
let boundFunc = func.bind(thisAtr[, arg1[, arg2[, ...argN]]])
+
+ +

Parametry

+ +
+
thisAtr
+
Wartość, która ma być przekazana jako this do funkcji docelowej func po wywołaniu funkcji powiązanej. Wartość jest ignorowana, jeśli funkcja powiązana jest konstruowana przy użyciu operatora {{jsxref („Operators / new”, „new”)}}. Podczas używania funkcji bind do utworzenia funkcji (dostarczonej jako wywołanie zwrotne) wewnątrz setTimeout, każda prymitywna wartość przekazywana, gdy thisAtr jest konwertowany na obiekt. Jeśli nie podano żadnych argumentów, aby powiązać (bind), lub jeśli thisArg jest null lub undefined, this z zakresu wykonania jest traktowany jako thisAtr dla nowej funkcji.
+
arg1, arg2, ...argN {{optional_inline}}
+
Argumenty poprzedzające argumenty dostarczone funkcji powiązanej podczas wywoływania func.
+
+ +

Zwracana wartość

+ +

Kopia podanej funkcji z podaną tą wartością i początkowymi argumentami (jeśli podano).

+ +

Opis

+ +

Funkcja bind() tworzy nową funkcję wiązania (bound function), która jest exotic function object (termin z ECMAScript 2015), który zawija oryginalny obiekt funkcji. Wywołanie funkcji powiązanej zazwyczaj skutkuje wykonaniem jej owrapowanej funkcji.

+ +

Funckja wiązania (bound function) ma następujące właściwości wewnętrzne:

+ +
+
[[BoundTargetFunction]]
+
The wrapped function object
+
[[BoundThis]]
+
The value that is always passed as this value when calling the wrapped function.
+
[[BoundArguments]]
+
A list of values whose elements are used as the first arguments to any call to the wrapped function.
+
[[Call]]
+
Executes code associated with this object. Invoked via a function call expression. The arguments to the internal method are a this value and a list containing the arguments passed to the function by a call expression.
+
+ +

When a bound function is called, it calls internal method [[Call]] on [[BoundTargetFunction]], with following arguments Call(boundThis, ...args). Where boundThis is [[BoundThis]], args is [[BoundArguments]], followed by the arguments passed by the function call.

+ +

A bound function may also be constructed using the {{jsxref("Operators/new", "new")}} operator. Doing so acts as though the target function had instead been constructed. The provided this value is ignored, while prepended arguments are provided to the emulated function.

+ +

Examples

+ +

Creating a bound function

+ +

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

+ +

A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).

+ +

Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:

+ +
this.x = 9;    // 'this' refers to global 'window' object here in a browser
+const module = {
+  x: 81,
+  getX: function() { return this.x; }
+};
+
+module.getX();
+//  returns 81
+
+const retrieveX = module.getX;
+retrieveX();
+//  returns 9; the function gets invoked at the global scope
+
+//  Create a new function with 'this' bound to module
+//  New programmers might confuse the
+//  global variable 'x' with module's property 'x'
+const boundGetX = retrieveX.bind(module);
+boundGetX();
+//  returns 81
+
+ +

Funkcje częściowo zastosowane
+ Kolejnym najprostszym zastosowaniem bind () jest utworzenie funkcji z wcześniej określonymi argumentami początkowymi.

+ +

Argumenty te (jeśli występują) są zgodne z podaną wartością, a następnie są wstawiane na początku argumentów przekazywanych do funkcji docelowej, a następnie wszelkie argumenty przekazywane funkcja powiązana w momencie jej wywołania.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+function addArguments(arg1, arg2) {
+  return arg1 + arg2
+}
+
+const list1 = list(1, 2, 3);
+//  [1, 2, 3]
+
+const result1 = addArguments(1, 2);
+//  3
+
+// Create a function with a preset leading argument
+const leadingThirtysevenList = list.bind(null, 37);
+
+// Create a function with a preset first argument.
+const addThirtySeven = addArguments.bind(null, 37);
+
+const list2 = leadingThirtysevenList();
+//  [37]
+
+const list3 = leadingThirtysevenList(1, 2, 3);
+//  [37, 1, 2, 3]
+
+const result2 = addThirtySeven(5);
+//  37 + 5 = 42
+
+const result3 = addThirtySeven(5, 10);
+//  37 + 5 = 42
+//  (the second argument is ignored)
+
+
+
+ +

With setTimeout()

+ +

By default within window.setTimeout(), the this keyword will be set to the window (or global) object. When working with class methods that require this to refer to class instances, you may explicitly bind this to the callback function, in order to maintain the instance.

+ +
function LateBloomer() {
+  this.petalCount = Math.floor(Math.random() * 12) + 1;
+}
+
+// Declare bloom after a delay of 1 second
+LateBloomer.prototype.bloom = function() {
+  window.setTimeout(this.declare.bind(this), 1000);
+};
+
+LateBloomer.prototype.declare = function() {
+  console.log(`I am a beautiful flower with ${this.petalCount} petals!`);
+};
+
+const flower = new LateBloomer();
+flower.bloom();
+//  after 1 second, calls 'flower.declare()'
+
+ +

Funkcje powiązane używane jako kostruktory

+ +
+

Ostrzeżenie: ta sekcja pokazuje możliwości JavaScript i dokumentuje niektóre przypadki krawędzi metody bind ().

+ +

Metody przedstawione poniżej nie są najlepszym sposobem na robienie rzeczy i prawdopodobnie nie powinny być stosowane w żadnym środowisku produkcyjnym.

+
+ +

Funkcje powiązane są automatycznie odpowiednie do użycia z operatorem {{jsxref („Operators / new”, „new”)}} do tworzenia nowych instancji utworzonych przez funkcję docelową. Gdy do utworzenia wartości używana jest funkcja powiązana, pod warunkiem, że jest to ignorowane.

+ +

Jednak pod warunkiem, że argumenty są nadal dołączane do wywołania konstruktora:

+ +
function Point(x, y) {
+  this.x = x;
+  this.y = y;
+}
+
+Point.prototype.toString = function() {
+  return `${this.x},${this.y}`;
+};
+
+const p = new Point(1, 2);
+p.toString();
+// '1,2'
+
+
+//  not supported in the polyfill below,
+
+//  works fine with native bind:
+
+const YAxisPoint = Point.bind(null, 0/*x*/);
+
+
+const emptyObj = {};
+const YAxisPoint = Point.bind(emptyObj, 0/*x*/);
+
+const axisPoint = new YAxisPoint(5);
+axisPoint.toString();                    // '0,5'
+
+axisPoint instanceof Point;              // true
+axisPoint instanceof YAxisPoint;         // true
+new YAxisPoint(17, 42) instanceof Point; // true
+
+ +

Zauważ, że nie musisz robić nic specjalnego, aby utworzyć powiązaną funkcję do użycia z {{jsxref („Operators / new”, „new”)}}.

+ +

Następstwem jest to, że nie musisz robić nic specjalnego, aby utworzyć funkcję powiązaną, która będzie wywoływana w sposób jawny, nawet jeśli wolisz, aby funkcja powiązana była wywoływana tylko za pomocą {{jsxref („Operators / new”, „new”)}} .

+ +
//  Example can be run directly in your JavaScript console
+//  ...continued 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.

+ +

Tworzenie skrótów

+ +

bind () jest również pomocny w przypadkach, w których chcesz utworzyć skrót do funkcji, która wymaga podania tej wartości.

+ +

Weźmy na przykład {{jsxref ("Array.prototype.slice ()")}}, którego chcesz użyć do konwersji obiektu podobnego do tablicy na prawdziwą tablicę. Możesz utworzyć taki skrót:

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

Za pomocą bind () można to uprościć.

+ +

W poniższym fragmencie kodu slice () jest funkcją powiązaną z funkcją {{jsxref („Function.prototype.apply ()”, „Apply ()”)}} z {{jsxref („Function.prototype”) }}, z tą wartością ustawioną na {{jsxref („Array.prototype.slice ()”, „slice ()”)}} funkcji {{jsxref („Array.prototype”)}}. Oznacza to, że dodatkowe wywołania apply () można wyeliminować:

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

Polyfill
+ Ponieważ starsze przeglądarki są na ogół również wolniejszymi przeglądarkami, jest to o wiele bardziej krytyczne niż większość ludzi rozpoznaje tworzenie polifillów wydajności, aby przeglądanie w przestarzałych przeglądarkach było nieco mniej straszne.

+ +

W związku z tym poniżej przedstawiono dwie opcje dla funkcji wypełniania funkcji Function.prototype.bind ():

+ +

Pierwszy jest znacznie mniejszy i bardziej wydajny, ale nie działa, gdy używasz nowego operatora.
+ Drugi jest większy i mniej wydajny, ale pozwala na pewne użycie nowego operatora na powiązanych funkcjach.
+ Zasadniczo w większości kodów bardzo rzadko widuje się nowe używane w funkcji powiązanej, więc najlepiej jest wybrać pierwszą opcję.

+ +
//  Does not work with `new funcA.bind(thisArg, args)`
+if (!Function.prototype.bind) (function(){
+  var slice = Array.prototype.slice;
+  Function.prototype.bind = function() {
+    var thatFunc = this, thatArg = arguments[0];
+    var args = slice.call(arguments, 1);
+    if (typeof thatFunc !== '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');
+    }
+    return function(){
+      var funcArgs = args.concat(slice.call(arguments))
+      return thatFunc.apply(thatArg, funcArgs);
+    };
+  };
+})();
+ +

Możesz częściowo obejść ten problem, wstawiając następujący kod na początku skryptów, umożliwiając korzystanie z większości funkcji bind () w implementacjach, które nie obsługują go natywnie.

+ +
//  Yes, it does work with `new funcA.bind(thisArg, args)`
+if (!Function.prototype.bind) (function(){
+  var ArrayPrototypeSlice = Array.prototype.slice;
+  Function.prototype.bind = function(otherThis) {
+    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 baseArgs= ArrayPrototypeSlice .call(arguments, 1),
+        baseArgsLength = baseArgs.length,
+        fToBind = this,
+        fNOP    = function() {},
+        fBound  = function() {
+          baseArgs.length = baseArgsLength; // reset to default base arguments
+          baseArgs.push.apply(baseArgs, arguments);
+          return fToBind.apply(
+                 fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs
+          );
+        };
+
+    if (this.prototype) {
+      // Function.prototype doesn't have a prototype property
+      fNOP.prototype = this.prototype;
+    }
+    fBound.prototype = new fNOP();
+
+    return fBound;
+  };
+})();
+
+ +

Niektóre z wielu różnic (mogą być też inne, ponieważ ta lista nie próbuje być wyczerpująca) między tym algorytmem a określonym algorytmem to:

+ +

Częściowa implementacja opiera się na {{jsxref ("Array.prototype.slice ()")}}, {{jsxref ("Array.prototype.concat ()")}}, {{jsxref ("Function.prototype.call ( ) ")}} i {{jsxref (" Function.prototype.apply () ")}}, wbudowane metody mające swoje oryginalne wartości.
+ Częściowa implementacja tworzy funkcje, które nie mają niezmiennej „pigułki trucizny” {{jsxref („Function.caller”, „caller”)}} i właściwości argumentów, które wyrzucają {{jsxref („Global_Objects / TypeError”, „TypeError”) }} przy pobieraniu, ustawianiu lub usuwaniu. (Można to dodać, jeśli implementacja obsługuje {{jsxref („Object.defineProperty”)}} lub częściowo zaimplementowana [bez zachowania polegającego na rzucaniu przy usuwaniu], jeśli implementacja obsługuje {{jsxref („Object .__ zdefiniujGetter__”, „ __defineGetter__ ”)}} i {{jsxref („ Object .__ definiSetter__ ”,„ __defineSetter__ ”)}}).
+ Częściowa implementacja tworzy funkcje, które mają właściwość prototypu. (Właściwie powiązane funkcje nie mają żadnych.)
+ Częściowa implementacja tworzy powiązane funkcje, których właściwość {{jsxref („Function.length”, „length”)}}} nie zgadza się z właściwością nakazaną przez ECMA-262: tworzy funkcje o długości 0. Pełna implementacja - w zależności od długość funkcji docelowej i liczba wcześniej określonych argumentów - może zwrócić niezerową długość.
+ Częściowa implementacja tworzy powiązane funkcje, których właściwość {{jsxref („Function.name”, „name”)}} nie jest pochodną oryginalnej nazwy funkcji. Według ECMA-262 nazwa zwróconej funkcji powiązanej powinna być „związana” + nazwa funkcji docelowej.
+ Jeśli zdecydujesz się użyć tej częściowej implementacji, nie możesz polegać na przypadkach, w których zachowanie odbiega od ECMA-262, wydanie 5! Na szczęście te odchylenia od specyfikacji rzadko (jeśli w ogóle) pojawiają się w większości sytuacji kodowania. Jeśli nie rozumiesz żadnego z odchyleń od powyższej specyfikacji, w tym konkretnym przypadku można bezpiecznie nie martwić się o te niezgodne szczegóły odchylenia.

+ +

Jeśli jest to absolutnie konieczne, a wydajność nie stanowi problemu, znacznie wolniejsze (ale bardziej zgodne ze specyfikacją rozwiązanie) można znaleźć na stronie https://github.com/Raynos/function-bind.

+ +

Dane techniczne

+ + + + + + + + + + + + +
Specyfikacja
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}
+ +
Kompatybilność z przeglądarkami
+ Tabela zgodności na tej stronie jest generowana z danych strukturalnych. Jeśli chcesz przyczynić się do danych, sprawdź https://github.com/mdn/browser-compat-data i wyślij nam żądanie ściągnięcia.
+ {{Compat ("javascript.builtins.Function.bind")}}
+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/global_objects/function/caller/index.html b/files/pl/web/javascript/reference/global_objects/function/caller/index.html new file mode 100644 index 0000000000..1c86b7f92f --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/caller/index.html @@ -0,0 +1,69 @@ +--- +title: Function.caller +slug: Web/JavaScript/Referencje/Obiekty/Function/caller +tags: + - Function + - JavaScript + - Non-standard + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/caller +--- +
{{JSRef}} {{non-standard_header}}
+ +

Podsumowanie

+ +

Określa funkcję, która powołuje się na aktualnie wykonywaną funkcje.

+ +

Opis

+ +

Jeśli funkcja f została wywołana przez kod najwyższego poziomu, własność f.caller ma wartość {{jsxref("null")}}, w przeciwnym przypadku jest to funkcja, która wywołała f.

+ +

Ta własność zastąpiła wycofaną własność {{jsxref("arguments.caller")}}.

+ +

Notes

+ +

Note that in case of recursion, you can't reconstruct the call stack using this property. Consider:

+ +
function f(n) { g(n-1); }
+function g(n) { if(n>0) { f(n); } else { stop(); } }
+f(2);
+
+ +

At the moment stop() is called the call stack will be:

+ +
f(2) -> g(1) -> f(1) -> g(0) -> stop()
+
+ +

The following is true:

+ +
stop.caller === g && f.caller === g && g.caller === f
+
+ +

so if you tried to get the stack trace in the stop() function like this:

+ +
var f = stop;
+var stack = "Stack trace:";
+while (f) {
+  stack += "\n" + f.name;
+  f = f.caller;
+}
+
+ +

the loop would never stop.

+ +

Przykłady

+ +

Przykład: Sprawdzenie wartości własności funkcji caller

+ +

Następujący kod sprawdza wartość własności funkcji caller.

+ +
function myFunc() {
+   if (myFunc.caller == null) {
+      return ("The function was called from the top!");
+   } else {
+      return ("This function's caller was " + myFunc.caller);
+   }
+}
+
+ +
 
diff --git a/files/pl/web/javascript/reference/global_objects/function/displayname/index.html b/files/pl/web/javascript/reference/global_objects/function/displayname/index.html new file mode 100644 index 0000000000..72c8c41257 --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/displayname/index.html @@ -0,0 +1,119 @@ +--- +title: Function.displayName +slug: Web/JavaScript/Referencje/Obiekty/Function/displayName +translation_of: Web/JavaScript/Reference/Global_Objects/Function/displayName +--- +
{{JSRef}} {{non-standard_header}}
+ +

Właściwość function.displayName zwraca wyświetlaną nazwę funkcji.

+ +

Opis

+ +

Gdy jest zdefiniowana, wlaściwość displayName zwraca wyświetlaną nazwę funkcji:

+ +
function doSomething() {}
+
+console.log(doSomething.displayName); // "undefined"
+
+var popup = function(content) { console.log(content); };
+
+popup.displayName = 'Pokaż Popup';
+
+console.log(popup.displayName); // "Pokaż Popup"
+
+ +

Możesz zdefiniować funkcję z wyświetlaną nazwą {{jsxref("Functions", "function expression", "", 1)}}:

+ +
var object = {
+  someMethod: function() {}
+};
+
+object.someMethod.displayName = 'jakaśMetoda';
+
+console.log(object.someMethod.displayName); // logs "jakaśMetoda"
+
+try { someMethod } catch(e) { console.log(e); }
+// ReferenceError: jakaśMetoda is not defined
+
+ +

Możesz dynamicznie zmieniać displayName z funkcji:

+ +
var object = {
+  // anonymous
+  someMethod: function(value) {
+    this.displayName = 'jakaśMetoda (' + value + ')';
+  }
+};
+
+console.log(object.someMethod.displayName); // "undefined"
+
+object.someMethod('123')
+console.log(object.someMethod.displayName); // "jakaśMetoda (123)"
+
+ +

Przykłady

+ +

Zazwyczaj preferowane jest przez konsole i profilery podczas {{jsxref("Function.name", "func.name")}} aby wyświetlić nazwę funkcji.

+ +

Umieszczony w konsoli powinien wyświetlić coś w rodzaju "function Moja Funkcja()":

+ +
var a = function() {};
+a.displayName = 'Moja Funkcja';
+
+a; // "function Moja Funkcja()"
+ +

Specyfikacja

+ +

Nie jest częścią żadnej specyfikacji.

+ +

Zgodność z przeglądarką

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(13)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pl/web/javascript/reference/global_objects/function/index.html b/files/pl/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..2db4d33411 --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,237 @@ +--- +title: Function +slug: Web/JavaScript/Referencje/Obiekty/Function +tags: + - Function + - JavaScript + - Konstruktor +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Konstruktor Function tworzy nowy obiekt Function(tworzy funkcję poprzez konstruktor). W JavaScripcie właściwie każda funkcja jest obiektem Function.

+ +

Składnia

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

Parametry

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

Opis

+ +

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("Global_Objects/eval", "eval")}} with code for a function expression.

+
+ +

Wywołanie konstruktora Function jako funkcję (bez użycia operatora 'new') ma taki sam efekt jak wywołanie konstruktora(z operatorem).

+ +

Właściwości i metody 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

+ +

Właściwości

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

Metody

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

+ +

Przykłady

+ +

Przykład: Specifying arguments with the Function constructor

+ +

Poniższy przykład tworzy obiekt Function(tworzy funkcję poprzez konstruktor), który przyjmuje dwa argumenty.

+ +
// Przykład może być uruchomiony bezpośrednio w konsoli JavaScript
+
+// Tworzy funkcję, która przyjmuje dwa argumenty i zwraca ich sumę
+var adder = new Function('a', 'b', 'return a + b');
+
+// Wywołanie funkcji
+adder(2, 6);
+// > 8
+
+ +

Argumenty "a" i "b" są formanie nazwami argumentrów, które są użyte w ciele funkcji, "return a + b".

+ +

Przykład: 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>
+ +

 

+ +

Specyfikacja

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
+ +

Kompatybilność z przeglądarkami

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

Zobacz również

+ + diff --git a/files/pl/web/javascript/reference/global_objects/function/length/index.html b/files/pl/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..e34ecb8154 --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,42 @@ +--- +title: Function.length +slug: Web/JavaScript/Referencje/Obiekty/Function/length +tags: + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +

{{JSRef}}

+ +

Podsumowanie

+ +

Określa liczbę argumentów oczekiwanych przez funkcję.

+ +

Opis

+ +

Obiekt length znajduje się na zewnątrz funkcji i określa jak wiele argumentów ma oczekiwać funkcja, i.e. liczbę oficjalnych parametrów. W przeciwieństwie do obiektu {{jsxref("arguments.length")}}, który znajduje się wewnątrz funkcji, określa liczbę argumentów faktycznie przekazywanych do funkcji.

+ +

Przykład

+ +

Przykład: Zastosowanie Function.length i arguments.length

+ +

Następujący przykład pokazuje w jaki należy zastosować Function.length i arguments.length.

+ +
function addNumbers(x, y){
+   if (arguments.length == addNumbers.length) {
+      return (x + y);
+   }
+   else
+      return 0;
+}
+
+ +

Jeśli podamy więcej niż dwa argumenty do tej funkcji, funkcja zwróci 0:

+ +
addNumbers(3,4,5)   // zwraca 0
+addNumbers(3,4)     // zwraca 7
+addNumbers(103,104) // zwraca 207
+
+ +
 
diff --git a/files/pl/web/javascript/reference/global_objects/function/tostring/index.html b/files/pl/web/javascript/reference/global_objects/function/tostring/index.html new file mode 100644 index 0000000000..2f158219b9 --- /dev/null +++ b/files/pl/web/javascript/reference/global_objects/function/tostring/index.html @@ -0,0 +1,56 @@ +--- +title: Function.prototype.toString() +slug: Web/JavaScript/Referencje/Obiekty/Function/toString +tags: + - Function + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Function/toString +--- +
{{JSRef}}
+ +

Podsumowanie

+ +

Zwraca łańcuch znaków reprezentujący kod źródłowy funkcji.

+ +

Składnia

+ +
function.toString(indentation)
+ +

Parametry

+ +
+
indentation {{non-standard_inline}} {{obsolete_inline(17)}}
+
The amount of spaces to indent the string representation of the source code. If indentation is less than or equal to -1, most unnecessary spaces are removed.
+
+ +

Opis

+ +

Obiekt {{jsxref("Function")}} przesłania metodę {{jsxref("Object.prototype.toString", "toString")}} obiektu {{jsxref("Function")}}; nie dziedziczy {{jsxref("Object.prototype.toString")}}. Dla obiektów Function, metoda toString() zwraca łańcuch znaków reprezentujący obiekt.

+ +

JavaScript wywołuje metodę toString() automatycznie, gdy {{jsxref("Function")}} jest reprezentowana jako wartość tekstowa lub kiedy Function jest odsyłana do połączenia łańcuchów znaków.

+ +

Dla obiektów {{jsxref("Function")}}, wbudowana metoda toString)= dekompiluje funkcję z powrotem do kodu JavaScript, który tę funkcję definiuje. Łańcuch znaków zawiera słowa kluczowe function, listę argumentów, nawiasy klamrowe oraz ciało funkcji.

+ +

Załóżmy na przykład, że masz poniższy kod, który definiuje obiektowy typ Dog i tworzy theDog, obiekt typu Dog:

+ +
function Dog(name, breed, color, sex) {
+   this.name = name
+   this.breed = breed
+   this.color = color
+   this.sex = sex
+}
+
+theDog = new Dog( "Gabby", "Lab", "chocolate", "girl" );
+
+ +

W dowolnej chwili, gdy Dog jest użyty w kontekście jako łańcuch znaków, JavaScript automatycznie wywołuje funkcję toString, która zwraca poniższy łańcuch znaków:

+ +
function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; }
+ +

Zobacz także

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