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
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Первые предложения по улучшению перевода. Также подпишите CLA.
1-js/04-object-basics/06-constructor-new/1-two-functions-one-object/task.md
Outdated
Show resolved
Hide resolved
1-js/04-object-basics/06-constructor-new/1-two-functions-one-object/solution.md
Outdated
Show resolved
Hide resolved
1-js/04-object-basics/06-constructor-new/2-calculator-constructor/task.md
Outdated
Show resolved
Hide resolved
1-js/04-object-basics/06-constructor-new/2-calculator-constructor/task.md
Outdated
Show resolved
Hide resolved
1-js/04-object-basics/06-constructor-new/2-calculator-constructor/task.md
Outdated
Show resolved
Hide resolved
Please make the requested changes. After it, add a comment "/done". |
/done |
/done |
Подскажите, есть ли еще какие-то замечания по переводу или можно приступать к другому разделу? |
There was a problem hiding this 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")`, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Отличные варианты)
/done |
@@ -78,7 +78,7 @@ let user = new function() { | |||
// локальные переменные и т. д. | |||
}; | |||
``` | |||
Функция-конструктор не может быть вызвана дважды, так как данные о ней нигде не сохраняются, просто создаются и вызываются. Таким образом, такой метод создания позволяет инкапсулировать код, который создаёт отдельный объект без дальнейшего использования. | |||
Конструктор не может быть вызван дважды, так как данные о ней нигде не сохраняются, просто создаются и вызываются. Таким образом, такой метод создания позволяет инкапсулировать код, который создаёт отдельный объект без дальнейшего пере использования. |
There was a problem hiding this comment.
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` работали одинаково. Поэтому, в примере ниже мы создаем два одинаковых объекта. |
There was a problem hiding this comment.
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`, мы точно знаем, что в итоге будет создан новый объект. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
кавычки убери плиз
Please make the requested changes. After it, add a comment "/done". |
/done |
|
||
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. | ||
Обычный синтаксис `{...}` позволяет создать только один объект. Но зачастую нам нужно создать множество однотипных объектов, таких как список пользователей, элементы меню и т.д. |
There was a problem hiding this comment.
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"`. |
There was a problem hiding this comment.
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 | ||
// ...любой другой пользовательский код |
There was a problem hiding this comment.
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" переведено как "любой другой пользовательский код" ? Это же явно разные по смыслу предложения.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне показалось, что такой перевод больше передает смысл.
Если нужно максимально близко к тексту, то предлагаю такой вариант: "другой код для создания пользователя"
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
там смысл именно в том, что внутри конструктора находится код для создания пользователя, а не просто "любой другой", поэтому лучше поменять, да.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Понял, правки внес.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Спасибо! Смотрю дальше?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, можно смотреть.
Please make the requested changes. After it, add a comment "/done". |
There was a problem hiding this 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. | ||
Такой конструктор не может быть вызван дважды, так как данные о ней нигде не сохраняются, просто создаются и вызываются. Таким образом, такой метод создания позволяет инкапсулировать код, который создаёт отдельный объект без дальнейшего пере использования. |
There was a problem hiding this comment.
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 | ||
## Проверка вызова конструктора |
There was a problem hiding this comment.
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="Проверка вызова конструктора" | ||
Данный метод используется очень редко. Вы можете пропустить данный блок, если не хотите углубляться в детали языка. |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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` работали одинаково. Поэтому, в примере ниже мы создаем два одинаковых объекта. |
There was a problem hiding this comment.
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. | ||
Пропуск скобок считается «Плохой практикой», но синтаксис языка этого не запрещает. |
There was a problem hiding this comment.
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. | ||
Использование конструкторов для создания объектов даёт большую гибкость. Можно передавать конструктору параметры, определяющие, как создавать объект, и он будет создавать объекты заданным образом. |
There was a problem hiding this comment.
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`: |
There was a problem hiding this comment.
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. | ||
- Функции-конструкторы, или просто, конструкторы, являются обычными функциями, именовать которые следует с заглавной буквы. |
There was a problem hiding this comment.
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` и многие другие, которые нам еще предстоит выучить. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
, например, Date
, Set
и других, которые нам ещё предстоит изучить.
Please make the requested changes. After it, add a comment "/done". |
/done |
🎉 |
Добрый день!
Добавил переведенную версию раздела "06-constructor-new", подскажите, есть ли какие-то замечания по переводу? Если все подходит, готов помочь с другими разделами.