Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1-js/04-object-basics/06-constructor-new #127

Merged
merged 27 commits into from May 10, 2019

Conversation

HomeDAN
Copy link
Contributor

@HomeDAN HomeDAN commented May 1, 2019

Добрый день!

Добавил переведенную версию раздела "06-constructor-new", подскажите, есть ли какие-то замечания по переводу? Если все подходит, готов помочь с другими разделами.

@javascript-translate-bot javascript-translate-bot added the review needed Review needed, please approve or request changes label May 1, 2019
@CLAassistant
Copy link

CLAassistant commented May 1, 2019

CLA assistant check
All committers have signed the CLA.

Copy link
Member

@lex111 lex111 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Первые предложения по улучшению перевода. Также подпишите CLA.

@javascript-translate-bot javascript-translate-bot added changes requested Waiting for changes and /done from PR author and removed review needed Review needed, please approve or request changes labels May 3, 2019
@javascript-translate-bot
Copy link
Contributor

Please make the requested changes. After it, add a comment "/done".
Then I'll ask for a new review 👻

@HomeDAN
Copy link
Contributor Author

HomeDAN commented May 3, 2019

/done

@javascript-translate-bot javascript-translate-bot added review needed Review needed, please approve or request changes and removed changes requested Waiting for changes and /done from PR author labels May 3, 2019
@HomeDAN
Copy link
Contributor Author

HomeDAN commented May 4, 2019

/done

@HomeDAN
Copy link
Contributor Author

HomeDAN commented May 4, 2019

Подскажите, есть ли еще какие-то замечания по переводу или можно приступать к другому разделу?

@javascript-translate-bot javascript-translate-bot added the changes requested Waiting for changes and /done from PR author label May 9, 2019
@iliakan iliakan added the partially reviewed Last review only took a part of the article. Full re-review (not just changes since last) required label May 9, 2019
Copy link
Contributor Author

@HomeDAN HomeDAN left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Илья, добрый день!

Внес правки. Прошу прощения за такое количество правок, буду пытаться максимально придерживаться оригинала.

Жду ваших замечаний по переводу) надеюсь финальных))))

isAdmin: false
};
```

Now if we want to create other users, we can call `new User("Ann")`, `new User("Alice")` and so on. Much shorter than using literals every time, and also easy to read.
Теперь, когда нам необходимо будет создать других пользователей, мы можем использовать `new User("Ann")`,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отличные варианты)

@HomeDAN
Copy link
Contributor Author

HomeDAN commented May 9, 2019

/done

@javascript-translate-bot javascript-translate-bot added review needed Review needed, please approve or request changes and removed changes requested Waiting for changes and /done from PR author labels May 9, 2019
@@ -78,7 +78,7 @@ let user = new function() {
// локальные переменные и т. д.
};
```
Функция-конструктор не может быть вызвана дважды, так как данные о ней нигде не сохраняются, просто создаются и вызываются. Таким образом, такой метод создания позволяет инкапсулировать код, который создаёт отдельный объект без дальнейшего использования.
Конструктор не может быть вызван дважды, так как данные о ней нигде не сохраняются, просто создаются и вызываются. Таким образом, такой метод создания позволяет инкапсулировать код, который создаёт отдельный объект без дальнейшего пере использования.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такой конструктор не может быть вызван дважды, так как данные о нём...

@@ -107,7 +107,7 @@ new User(); // function User { ... }
*/!*
```

Ниже приведённый пример можно использовать для того чтобы вызов функции при помощи оператора `new` и без него работали одинаково.
Данное свойство используется для того чтобы обычный вызов функции или при помощи оператора `new` работали одинаково. Поэтому, в примере ниже мы создаем два одинаковых объекта.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

, чтобы

@@ -124,7 +124,7 @@ alert(john.name); // Вася

Такой подход иногда используется в библиотеках для создания более гибкого синтаксиса, который позволяет разработчикам вызывать функции при помощи оператора `new` или без него.

Вызов функции-конструктора без оператора new является «плохой практикой», так как отсутствие `new` может ввести разработчика в заблуждение. С оператором new, мы точно знаем, что в итоге будет создан новый объект.
Вызов функции-конструктора без оператора `new` является «плохой практикой», так как отсутствие `new` может ввести разработчика в заблуждение. С оператором `new`, мы точно знаем, что в итоге будет создан новый объект.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

кавычки убери плиз

@javascript-translate-bot javascript-translate-bot added changes requested Waiting for changes and /done from PR author and removed review needed Review needed, please approve or request changes labels May 9, 2019
@javascript-translate-bot
Copy link
Contributor

Please make the requested changes. After it, add a comment "/done".
Then I'll ask for a new review 👻

@HomeDAN
Copy link
Contributor Author

HomeDAN commented May 9, 2019

/done

@javascript-translate-bot javascript-translate-bot added review needed Review needed, please approve or request changes and removed changes requested Waiting for changes and /done from PR author labels May 9, 2019

The regular `{...}` syntax allows to create one object. But often we need to create many similar objects, like multiple users or menu items and so on.
Обычный синтаксис `{...}` позволяет создать только один объект. Но зачастую нам нужно создать множество однотипных объектов, таких как список пользователей, элементы меню и т.д.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

таких как пользователи


That can be done using constructor functions and the `"new"` operator.
Всё это возможно благодаря функциям-конструкторам и оператору `"new"`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это можно сделать при помощи функции-конструктора и оператора new.

// ...other code for user creation
// maybe complex logic and statements
// local variables etc
// ...любой другой пользовательский код
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

почему "other code for user creation" переведено как "любой другой пользовательский код" ? Это же явно разные по смыслу предложения.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне показалось, что такой перевод больше передает смысл.

Если нужно максимально близко к тексту, то предлагаю такой вариант: "другой код для создания пользователя"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

там смысл именно в том, что внутри конструктора находится код для создания пользователя, а не просто "любой другой", поэтому лучше поменять, да.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Понял, правки внес.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спасибо! Смотрю дальше?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, можно смотреть.

@javascript-translate-bot javascript-translate-bot added changes requested Waiting for changes and /done from PR author and removed review needed Review needed, please approve or request changes labels May 9, 2019
@javascript-translate-bot
Copy link
Contributor

Please make the requested changes. After it, add a comment "/done".
Then I'll ask for a new review 👻

Copy link
Member

@iliakan iliakan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пожалуйста, внеси исправления.

};
```

The constructor can't be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.
Такой конструктор не может быть вызван дважды, так как данные о ней нигде не сохраняются, просто создаются и вызываются. Таким образом, такой метод создания позволяет инкапсулировать код, который создаёт отдельный объект без дальнейшего пере использования.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такой конструктор не может быть вызван дважды, так как он нигде не сохраняется, просто создается и тут же вызывается.

````

## Dual-syntax constructors: new.target
## Проверка вызова конструктора
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проверка вызова конструктора: new.target

```smart header="Advanced stuff"
The syntax from this section is rarely used, skip it unless you want to know everything.
```smart header="Проверка вызова конструктора"
Данный метод используется очень редко. Вы можете пропустить данный блок, если не хотите углубляться в детали языка.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

данный блок -> эту секцию


It is empty for regular calls and equals the function if called with `new`:
В случае, если функция вызвана при помощи оператор `new`, то вернётся тело функции, в противном случае вызов вернёт undefined.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В случае, если функция вызвана при помощи new, то в new.target будет сама функция, в противном случае вызов вернёт undefined.

*!*
new User(); // function User { ... }
*/!*
```

That can be used to allow both `new` and regular calls to work the same. That is, create the same object:
Данное свойство используется для того, чтобы обычный вызов функции или при помощи оператора `new` работали одинаково. Поэтому, в примере ниже мы создаем два одинаковых объекта.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это можно использовать, чтобы отличить обычный вызов от вызова "в режиме конструктора". В частности, вот так можно сделать, чтобы функцию можно было вызывать как с, так и без new:

// same as
let user = new User();
```

Omitting parentheses here is not considered a "good style", but the syntax is permitted by specification.
Пропуск скобок считается «Плохой практикой», но синтаксис языка этого не запрещает.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

плохой практикой - без кавычек


Using constructor functions to create objects gives a great deal of flexibility. The constructor function may have parameters that define how to construct the object, and what to put in it.
Использование конструкторов для создания объектов даёт большую гибкость. Можно передавать конструктору параметры, определяющие, как создавать объект, и он будет создавать объекты заданным образом.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как создавать объект, и что в него записывать.


For instance, `new User(name)` below creates an object with the given `name` and the method `sayHi`:
Например, в примере ниже, `new User(name)` создаёт объект с переданным в него `name` и методом `sayHi`:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...с данным именем name и методом..


We can use constructor functions to make multiple similar objects.
- Функции-конструкторы, или просто, конструкторы, являются обычными функциями, именовать которые следует с заглавной буквы.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Функции-конструкторы или просто конструкторы являются...


```smart header="Objects, we'll be back!"
In this chapter we only cover the basics about objects and constructors. They are essential for learning more about data types and functions in the next chapters.
JavaScript предоставляет функции-конструкторы для множества встроенных объектов языка: например, такие как `Date`, `Set` и многие другие, которые нам еще предстоит выучить.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

, например, Date, Set и других, которые нам ещё предстоит изучить.

@javascript-translate-bot
Copy link
Contributor

Please make the requested changes. After it, add a comment "/done".
Then I'll ask for a new review 👻

@iliakan iliakan removed the partially reviewed Last review only took a part of the article. Full re-review (not just changes since last) required label May 9, 2019
@HomeDAN
Copy link
Contributor Author

HomeDAN commented May 10, 2019

/done

@javascript-translate-bot javascript-translate-bot added review needed Review needed, please approve or request changes and removed changes requested Waiting for changes and /done from PR author labels May 10, 2019
@iliakan
Copy link
Member

iliakan commented May 10, 2019

🎉

@iliakan iliakan merged commit 4ec93d9 into javascript-tutorial:master May 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs +1 One more review needed review needed Review needed, please approve or request changes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants