|
1 | | -## The `for in` Loop |
| 1 | +## Цикл `for in` |
2 | 2 |
|
3 | | -Just like the `in` operator, the `for in` loop also traverses the prototype |
4 | | -chain when iterating over the properties of an object. |
| 3 | +Как и оператор `in`, цикл `for in` проходит по всей цепочке прототипов обходя свойства объекта. |
5 | 4 |
|
6 | | -> **Note:** The `for in` loop will **not** iterate over any properties that |
7 | | -> have their `enumerable` attribute set to `false`; for example, the `length` |
8 | | -> property of an array. |
9 | | - |
10 | | - // Poisoning Object.prototype |
| 5 | +> **Примечание:** Цикл `for in` **не** обходит те свойства объекта, у которых атрибут `enumerable` установлен в `false`; как пример - свойство `length` у массивов |
| 6 | +
|
| 7 | + // Испортим Object.prototype |
11 | 8 | Object.prototype.bar = 1; |
12 | 9 |
|
13 | 10 | var foo = {moo: 2}; |
14 | 11 | for(var i in foo) { |
15 | | - console.log(i); // prints both bar and moo |
| 12 | + console.log(i); // печатает и bar и moo |
16 | 13 | } |
17 | 14 |
|
18 | | -Since it is not possible to change the behavior of the `for in` loop itself, it |
19 | | -is necessary to filter out the unwanted properties inside the loop body , |
20 | | -this is done by using the [`hasOwnProperty`](#object.hasownproperty) method of |
21 | | -`Object.prototype`. |
| 15 | +Так как изменить поведение цикла `for in` как такового не представляется возможным, то для фильтрации нежелательных свойств объекта внутри этого цикла используют метод [`hasOwnProperty`](#object.hasownproperty) из `Object.prototype`. |
22 | 16 |
|
23 | | -> **Note:** Since the `for in` always traverses the complete prototype chain, it |
24 | | -> will get slower with each additional layer of inheritance added to an object. |
| 17 | +> **Примечание:** Цикл `for in` всегда обходит всю цепочку прототипов полностью: таким образом, чем больше прототипов (слоёв наследования) в цепочке, тем медленнее работает цикл. |
25 | 18 |
|
26 | | -### Using `hasOwnProperty` for filtering |
| 19 | +### Использование `hasOwnProperty` в качестве фильтра |
27 | 20 |
|
28 | | - // still the foo from above |
| 21 | + // возьмём foo из примера выше |
29 | 22 | for(var i in foo) { |
30 | 23 | if (foo.hasOwnProperty(i)) { |
31 | 24 | console.log(i); |
32 | 25 | } |
33 | 26 | } |
34 | 27 |
|
35 | | -This version is the only correct one to use. Due to the use of `hasOwnPropery` it |
36 | | -will **only** print out `moo`. When `hasOwnProperty` is left out, the code is |
37 | | -prone to errors in cases where the native prototypes - e.g. `Object.prototype` - |
38 | | -have been extended. |
| 28 | +Эта единственная версия правильного использования. Благодаря использованию `hasOwnPropery` будет выведен **только** `moo`. Если же убрать `hasOwnProperty`, код становится нестабилен и могут возникнуть ошибки, если кто-то изменил встроенные прототипы, такие как `Object.prototype`. |
39 | 29 |
|
40 | | -One widely used framework which does this is [Prototype][1]. When this |
41 | | -framework is included, `for in` loops that do not use `hasOwnProperty` are |
42 | | -guaranteed to break. |
| 30 | +Один из самых популярных фреймворков [Prototype][1] как раз этим и славится, и если вы его подключаете, то не забудьте использовать `hasOwnProperty` внутри цикла `for in`, иначе гарантированно возникнут проблемы. |
43 | 31 |
|
44 | | -### Best practices |
| 32 | +### Рекомендации |
45 | 33 |
|
46 | | -It is recommended to **always** use `hasOwnProperty`. Never should any |
47 | | -assumptions be made about the environment the code is running in, or whether the |
48 | | -native prototypes have been extended or not. |
| 34 | +Рекомендация одна — **всегда** используйте `hasOwnProperty`. пишите код, который будет в наименьшей мере зависеть от окружения в котором он будет запущен — не стоит гадать, расширял кто-то прототипы или нет и используется ли в ней та или иная библиотека. |
49 | 35 |
|
50 | 36 | [1]: http://www.prototypejs.org/ |
51 | 37 |
|
0 commit comments