|
1 | | -## `hasOwnProperty` |
| 1 | +## Функция `hasOwnProperty` |
2 | 2 |
|
3 | | -In order to check whether a object has a property defined on *itself* and **not** |
4 | | -somewhere on its [prototype chain](#object.prototype), it is necessary to use the |
5 | | -`hasOwnProperty` method which all objects inherit from `Object.prototype`. |
| 3 | +Если вам необходимо проверить, определено ли свойство у *самого объекта*, а **не** в его [цепочке прототипов](#object.prototype), вы можете использовать метод `hasOwnProperty`, который все объекты наследуют от `Object.prototype`. |
6 | 4 |
|
7 | | -> **Note:** It is **not** enough to check whether a property is `undefined`. The |
8 | | -> property might very well exist, but its value just happens to be set to |
9 | | -> `undefined`. |
| 5 | +> **Note:** Для проверки наличия свойства **недостаточно** проверять, эквивалентно ли оно `undefined`. Свойство может вполне себе существовать, но при этом ему может быть присвоено значение `undefined`. |
10 | 6 |
|
11 | | -`hasOwnProperty` is the only thing in JavaScript which deals with properties and |
12 | | -does **not** traverse the prototype chain. |
| 7 | +`hasOwnProperty` — единственная функция в JavaScript, которая позволяет получить свойства объекта **без обращения** к цепочке его прототипов. |
13 | 8 |
|
14 | | - // Poisoning Object.prototype |
15 | | - Object.prototype.bar = 1; |
| 9 | + // испортим Object.prototype |
| 10 | + Object.prototype.bar = 1; |
16 | 11 | var foo = {goo: undefined}; |
17 | | - |
| 12 | + |
18 | 13 | foo.bar; // 1 |
19 | 14 | 'bar' in foo; // true |
20 | 15 |
|
21 | 16 | foo.hasOwnProperty('bar'); // false |
22 | 17 | foo.hasOwnProperty('goo'); // true |
23 | 18 |
|
24 | | -Only `hasOwnProperty` will give the correct and expected result, this is |
25 | | -essential when iterating over the properties of any object. There is **no** other |
26 | | -way to exclude properties that are not defined on the object *itself*, but |
27 | | -somewhere on its prototype chain. |
| 19 | +Только используя hasOwnProperty можно гарантировать правильный результат при переборе свойств объекта. И **нет** иного способа для определения свойств, которые определены в *самом* объекте, а не где-то в цепочке прототипов. |
28 | 20 |
|
29 | | -### `hasOwnProperty` as a property |
| 21 | +### `hasOwnProperty` как свойство |
30 | 22 |
|
31 | | -JavaScript does **not** protect the property name `hasOwnProperty`; thus, if the |
32 | | -possibility exists that an object might have a property with this name, it is |
33 | | -necessary to use an *external* `hasOwnProperty` in order to get correct results. |
| 23 | +JavaScript **не** резервирует свойство с именем `hasOwnProperty`. Так что, если есть потенциальная возможность, что объект может содержать свойство с таким именем, требуется использовать *внешний* вариант функции `hasOwnProperty` чтобы получить корректные результаты. |
34 | 24 |
|
35 | 25 | var foo = { |
36 | 26 | hasOwnProperty: function() { |
37 | 27 | return false; |
38 | 28 | }, |
39 | | - bar: 'Here be dragons' |
| 29 | + bar: 'Да прилетят драконы' |
40 | 30 | }; |
41 | 31 |
|
42 | | - foo.hasOwnProperty('bar'); // always returns false |
| 32 | + foo.hasOwnProperty('bar'); // всегда возвращает false |
43 | 33 |
|
44 | | - // Use another hasOwnProperty and call it with 'this' set to foo |
| 34 | + // Используем метод hasOwnProperty пустого объекта |
| 35 | + // и передаём foo в качестве this |
45 | 36 | {}.hasOwnProperty.call(foo, 'bar'); // true |
46 | 37 |
|
47 | | -### In conclusion |
| 38 | +### Заключение |
48 | 39 |
|
49 | | -When checking for the existence of a property on a object, `hasOwnProperty` is |
50 | | -the **only** method of doing so. It is also recommended to make `hasOwnProperty` |
51 | | -part of **every** [`for in` loop](#object.forinloop), this will avoid errors from |
52 | | -extended native [prototypes](#object.prototype). |
| 40 | +**Единственным** способом проверить существование свойства у объекта является использование метода `hasOwnProperty`. При этом, рекомендуется использовать этот метод в **каждом** [цикле `for in`](#object.forinloop) вашего проекта, чтобы избежать возможных ошибок с ошибочным заимствованием свойств из [прототипов](#object.prototype) родительских объектов. Также вы можете использовать конструкцию `{}.hasOwnProperty.call(...)` на случай, если кто-то вздумает расширить [прототипы](#object.prototype) встроенных объектов. |
53 | 41 |
|
0 commit comments