You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
В области видимости любой функции в JavaScript есть доступ к специальной переменной `arguments`. Эта переменная содержит в себе список всех аргументов? переданных данной функции ghb dspjdt.
2
4
3
5
Every function scope in JavaScript can access the special variable `arguments`.
4
6
This variable holds a list of all the arguments that were passed to the function.
5
7
6
-
> **Note:** In case `arguments` has already been defined inside the function's
7
-
> scope either via a `var` statement or being the name of a formal parameter,
8
-
> the `arguments` object will not be created.
8
+
> **Замечание:** В случае, если переменная `arguments` уже была объявлена в области видимости функции либо путём присвоения через выражение `var`, либо являясь формальным параметром, объект `arguments` не будет создан.
9
9
10
-
The `arguments` object is **not** an `Array`. While it has some of the
11
-
semantics of an array - namely the `length` property - it does not inherit from
12
-
`Array.prototype` and is in fact an `Object`.
10
+
Объект `arguments`**не** является наследником `Array`. Он, конечно же, очень похож на массив, и даже содержит свойство `length` — но он не наследует `Array.prototype`, а представляет собой `Object`.
13
11
14
-
Due to this, it is **not** possible to use standard array methods like `push`,
15
-
`pop` or `slice` on `arguments`. While iteration with a plain `for` loop works
16
-
just fine, it is necessary to convert it to a real `Array` in order to use the
17
-
standard `Array` methods on it.
12
+
По этой причине, у объекта `arguments`**отсутствуют** стандартные методы массивов, такие как `push`, `pop` или `slice`. Хотя итерация с использованием обычного цикла `for` по агрументам работает вполне корректно, вам придётся конвертировать этот объект в настоящий массив типа `Array`, чтобы применять к нему стандартные методы массивов.
18
13
19
-
### Converting to an array
14
+
### Конвертация в массив
20
15
21
-
The code below will return a new `Array` containing all the elements of the
22
-
`arguments` object.
16
+
Указанный код вернёт новый массив типа `Array`, содержащий все элементы объекта `arguments`.
23
17
24
18
Array.prototype.slice.call(arguments);
25
19
26
-
This conversion is **slow**, it is **not recommended** to use it in performance
27
-
critical sections of code.
20
+
Эта конвертация занимает **много времени** и **не рекомендуется** использовать её в критических частях кода.
28
21
29
-
### Passing arguments
22
+
### Передача аргументов
30
23
31
-
The following is the recommended way of passing arguments from one function to
32
-
another.
24
+
Ниже представлен рекомендуемый способ передачи аргументов из одной функции в другую.
33
25
34
26
function foo() {
35
27
bar.apply(null, arguments);
36
28
}
37
29
function bar(a, b, c) {
38
-
// do stuff here
30
+
// делаем здесь что-либо
39
31
}
40
32
41
-
Another trick is to use both `call` and `apply` together to create fast, unbound
42
-
wrappers.
33
+
Другой трюк — использовать и `call` и `apply` вместе, чтобы быстро создать несвязанную обёртку:
43
34
44
35
function Foo() {}
45
36
46
37
Foo.prototype.method = function(a, b, c) {
47
38
console.log(this, a, b, c);
48
39
};
49
40
50
-
// Create an unbound version of "method"
51
-
// It takes the parameters: this, arg1, arg2...argN
41
+
// Создаём несвязанную версию "method"
42
+
// Она принимает параметры: this, arg1, arg2...argN
The `arguments` object creates *getter* and *setter* functions for both its
62
-
properties as well as the function's formal parameters.
53
+
Объект `arguments` создаёт по *геттеру* и *сеттеру* и для всех своих свойств и для формальных параметров функции.
63
54
64
-
As a result, changing the value of a formal parameter will also change the value
65
-
of the corresponding property on the `arguments` object, and the other way around.
55
+
В результате, изменение формального параметра также изменит значение соответствующего свойства объекта `arguments` и наоборот.
66
56
67
57
function foo(a, b, c) {
68
58
arguments[0] = 2;
69
-
a; // 2
59
+
a; // 2
70
60
71
61
b = 4;
72
62
arguments[1]; // 4
@@ -77,43 +67,32 @@ of the corresponding property on the `arguments` object, and the other way aroun
77
67
}
78
68
foo(1, 2, 3);
79
69
80
-
### Performance myths and truths
70
+
### Мифы и правда о производительности
81
71
82
-
The `arguments` object is always created with the only two exceptions being the
83
-
cases where it is declared as a name inside of a function or one of its formal
84
-
parameters. It does not matter whether it is used or not.
72
+
Объект `arguments` создаётся во всех случаях, лишь за двумя исключениямии — когда он переопределён по имени внутри функции или когда одним из её параметров является переменная с таким именем. Не важно, используется он при этом или нет.
85
73
86
-
Both *getters* and *setters* are **always** created; thus, using it has nearly
87
-
no performance impact at all, especially not in real world code where there is
88
-
more than a simple access to the `arguments` object's properties.
74
+
*Геттеры* и *сеттеры* создаются **всегда**; так что, их использование почти никак не влияет на производительность.
89
75
90
-
> **ES5 Note:**These *getters* and *setters* are not created in strict mode.
76
+
> **ES5 Замечание:**Эти *геттеры* и *сеттеры* не создаются в strict-режиме.
91
77
92
-
However, there is one case which will drastically reduce the performance in
93
-
modern JavaScript engines. That case is the use of `arguments.callee`.
78
+
Однако, есть один момент, который может радикально понизить производительность современных движков JavaScript. Этот момент — использование `arguments.callee`.
94
79
95
80
function foo() {
96
-
arguments.callee; // do something with this function object
97
-
arguments.callee.caller; // and the calling function object
81
+
arguments.callee; // сделать что-либо с этим объектом функции
82
+
arguments.callee.caller; // и с вызвавшим его объектом функции
98
83
}
99
84
100
85
function bigLoop() {
101
86
for(var i = 0; i < 100000; i++) {
102
-
foo(); // Would normally be inlined...
87
+
foo(); // При обычных условиях должна бы была быть развёрнута...
103
88
}
104
89
}
105
90
106
-
In the above code, `foo` can no longer be a subject to [inlining][1] since it
107
-
needs to know about both itself and its caller. This not only defeats possible
108
-
performance gains that would arise from inlining, it also breaks encapsulation
109
-
since the function may now be dependent on a specific calling context.
91
+
В коде выше, `foo` больше не может [быть развёрнута][1], потому что ей необходима ссылка и на себя, и на вызвавший объект. Это не только кладёт на лопатки механизм развёртывания, но и нарушает принцип инкапсуляции, поскольку функция становится зависима от конкретного контекста вызова.
110
92
111
-
It is **highly recommended** to **never** make use of `arguments.callee` or any of
112
-
its properties.
93
+
**Крайне рекомендуется****никогда** не использовать `arguments.callee` или его свойства.
113
94
114
-
> **ES5 Note:** In strict mode, `arguments.callee` will throw a `TypeError` since
115
-
> its use has been deprecated.
95
+
> **ES5 Замечание:** В strict-режиме `arguments.callee` выбросит `TypeError`, поскольку его использование принято устаревшим.
0 commit comments