Skip to content

Commit c4e4531

Browse files
committed
function/arguments
1 parent c85e2a5 commit c4e4531

File tree

1 file changed

+32
-53
lines changed

1 file changed

+32
-53
lines changed

doc/ru/function/arguments.md

Lines changed: 32 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,62 @@
1-
## The `arguments` Object
1+
## Объект `arguments`
2+
3+
В области видимости любой функции в JavaScript есть доступ к специальной переменной `arguments`. Эта переменная содержит в себе список всех аргументов? переданных данной функции ghb dspjdt.
24

35
Every function scope in JavaScript can access the special variable `arguments`.
46
This variable holds a list of all the arguments that were passed to the function.
57

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` не будет создан.
99
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`.
1311

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`, чтобы применять к нему стандартные методы массивов.
1813

19-
### Converting to an array
14+
### Конвертация в массив
2015

21-
The code below will return a new `Array` containing all the elements of the
22-
`arguments` object.
16+
Указанный код вернёт новый массив типа `Array`, содержащий все элементы объекта `arguments`.
2317

2418
Array.prototype.slice.call(arguments);
2519

26-
This conversion is **slow**, it is **not recommended** to use it in performance
27-
critical sections of code.
20+
Эта конвертация занимает **много времени** и **не рекомендуется** использовать её в критических частях кода.
2821

29-
### Passing arguments
22+
### Передача аргументов
3023

31-
The following is the recommended way of passing arguments from one function to
32-
another.
24+
Ниже представлен рекомендуемый способ передачи аргументов из одной функции в другую.
3325

3426
function foo() {
3527
bar.apply(null, arguments);
3628
}
3729
function bar(a, b, c) {
38-
// do stuff here
30+
// делаем здесь что-либо
3931
}
4032

41-
Another trick is to use both `call` and `apply` together to create fast, unbound
42-
wrappers.
33+
Другой трюк — использовать и `call` и `apply` вместе, чтобы быстро создать несвязанную обёртку:
4334

4435
function Foo() {}
4536

4637
Foo.prototype.method = function(a, b, c) {
4738
console.log(this, a, b, c);
4839
};
4940

50-
// Create an unbound version of "method"
51-
// It takes the parameters: this, arg1, arg2...argN
41+
// Создаём несвязанную версию "method"
42+
// Она принимает параметры: this, arg1, arg2...argN
5243
Foo.method = function() {
5344

54-
// Result: Foo.prototype.method.call(this, arg1, arg2... argN)
45+
// Результат: Foo.prototype.method.call(this, arg1, arg2... argN)
5546
Function.call.apply(Foo.prototype.method, arguments);
47+
5648
};
5749

5850

59-
### Formal parameters and arguments indexes
51+
### Формальные аргументы и индексы аргументов
6052

61-
The `arguments` object creates *getter* and *setter* functions for both its
62-
properties as well as the function's formal parameters.
53+
Объект `arguments` создаёт по *геттеру* и *сеттеру* и для всех своих свойств и для формальных параметров функции.
6354

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` и наоборот.
6656

6757
function foo(a, b, c) {
6858
arguments[0] = 2;
69-
a; // 2
59+
a; // 2
7060

7161
b = 4;
7262
arguments[1]; // 4
@@ -77,43 +67,32 @@ of the corresponding property on the `arguments` object, and the other way aroun
7767
}
7868
foo(1, 2, 3);
7969

80-
### Performance myths and truths
70+
### Мифы и правда о производительности
8171

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` создаётся во всех случаях, лишь за двумя исключениямии — когда он переопределён по имени внутри функции или когда одним из её параметров является переменная с таким именем. Не важно, используется он при этом или нет.
8573

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+
*Геттеры* и *сеттеры* создаются **всегда**; так что, их использование почти никак не влияет на производительность.
8975

90-
> **ES5 Note:** These *getters* and *setters* are not created in strict mode.
76+
> **ES5 Замечание:** Эти *геттеры* и *сеттеры* не создаются в strict-режиме.
9177
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`.
9479

9580
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; // и с вызвавшим его объектом функции
9883
}
9984

10085
function bigLoop() {
10186
for(var i = 0; i < 100000; i++) {
102-
foo(); // Would normally be inlined...
87+
foo(); // При обычных условиях должна бы была быть развёрнута...
10388
}
10489
}
10590

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], потому что ей необходима ссылка и на себя, и на вызвавший объект. Это не только кладёт на лопатки механизм развёртывания, но и нарушает принцип инкапсуляции, поскольку функция становится зависима от конкретного контекста вызова.
11092

111-
It is **highly recommended** to **never** make use of `arguments.callee` or any of
112-
its properties.
93+
**Крайне рекомендуется** **никогда** не использовать `arguments.callee` или его свойства.
11394

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`, поскольку его использование принято устаревшим.
11696
11797
[1]: http://en.wikipedia.org/wiki/Inlining
11898

119-

0 commit comments

Comments
 (0)