Skip to content

Constructor, operator "new" #172

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Yes, it's possible.
Так, це можливо.

If a function returns an object then `new` returns it instead of `this`.
Якщо функція повертає об’єкт, тоді `new` повертає його замість `this`.

So they can, for instance, return the same externally defined object `obj`:
Так функції `A` та `B` можуть, наприклад, повертати один і той самий об’єкт `obj`, визначений незалежно від цих функцій:

```js run no-beautify
let obj = {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 2

---

# Two functions – one object
# Дві функції - один об’єкт

Is it possible to create functions `A` and `B` so that `new A() == new B()`?
Чи можливо створити функції `A` та `B`, щоб `new A() == new B()`?

```js no-beautify
function A() { ... }
Expand All @@ -16,4 +16,4 @@ let b = new B;
alert( a == b ); // true
```

If it is, then provide an example of their code.
Якщо так -- наведіть приклад коду таких функцій.
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ describe("calculator", function() {
calculator = new Calculator();
calculator.read();
});
it("the read method asks for two values using prompt and remembers them in object properties", function() {

it("метод read запитує два значення за допомогою prompt і запам’ятовує їх у властивостях об’єкта", function() {
assert.equal(calculator.a, 2);
assert.equal(calculator.b, 3);
});

it("when 2 and 3 are entered, the sum is 5", function() {
it("при введенні 2 і 3 сума дорівнює 5", function() {
assert.equal(calculator.sum(), 5);
});

it("when 2 and 3 are entered, the product is 6", function() {
it("при введені 2 і 3, добуток дорівнює 6", function() {
assert.equal(calculator.mul(), 6);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ importance: 5

---

# Create new Calculator
# Створити Калькулятор за допомогою конструктора

Create a constructor function `Calculator` that creates objects with 3 methods:
Створіть функцію-конструктор `Calculator`, який створює об’єкти з трьома методами:

- `read()` asks for two values using `prompt` and remembers them in object properties.
- `sum()` returns the sum of these properties.
- `mul()` returns the multiplication product of these properties.
- `read()` запитує два значення за допомогою `prompt` і запам'ятовує їх у властивостях об’єкта.
- `sum()` повертає суму цих властивостей.
- `mul()` повертає результат множення даних властивостей.

For instance:
Наприклад:

```js
let calculator = new Calculator();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ function Accumulator(startingValue) {
this.value = startingValue;

this.read = function() {
this.value += +prompt('How much to add?', 0);
this.value += +prompt('Скільки додати?', 0);
};

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ describe("Accumulator", function() {
prompt.restore();
});

it("initial value is the argument of the constructor", function() {
it("початкове значення - це аргумент конструктора", function() {
let accumulator = new Accumulator(1);

assert.equal(accumulator.value, 1);
});

it("after reading 0, the value is 1", function() {
it("після прочитання 0 значення дорівнює 1", function() {
let accumulator = new Accumulator(1);
prompt.returns("0");
accumulator.read();
assert.equal(accumulator.value, 1);
});

it("after reading 1, the value is 2", function() {
it("після прочитання 1 значення дорівнює 2", function() {
let accumulator = new Accumulator(1);
prompt.returns("1");
accumulator.read();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ function Accumulator(startingValue) {
this.value = startingValue;

this.read = function() {
this.value += +prompt('How much to add?', 0);
this.value += +prompt('Скільки додати?', 0);
};

}
Expand Down
22 changes: 11 additions & 11 deletions 1-js/04-object-basics/06-constructor-new/3-accumulator/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,26 @@ importance: 5

---

# Create new Accumulator
# Створити Accumulator

Create a constructor function `Accumulator(startingValue)`.
Створіть функцію-конструктор `Accumulator(startingValue)`.

Object that it creates should:
Об’єкт, який він створює повинен:

- Store the "current value" in the property `value`. The starting value is set to the argument of the constructor `startingValue`.
- The `read()` method should use `prompt` to read a new number and add it to `value`.
- Зберігати "поточне значення" у властивості `value`. Початкове значення має значення аргументу конструктора `startingValue`.
- Метод `read()` повинен використовувати `prompt` для зчитування нового числа та додавати його до `value`.

In other words, the `value` property is the sum of all user-entered values with the initial value `startingValue`.
Іншими словами, властивість `value` -- це сума всіх введенних користувачем значень разом із початковим значенням `startingValue`.

Here's the demo of the code:
Нижче ви можете подивитись демонстрацію роботи коду:

```js
let accumulator = new Accumulator(1); // initial value 1
let accumulator = new Accumulator(1); // початкове значення 1

accumulator.read(); // adds the user-entered value
accumulator.read(); // adds the user-entered value
accumulator.read(); // додає введене користувачем значення
accumulator.read(); // додає введене користувачем значення

alert(accumulator.value); // shows the sum of these values
alert(accumulator.value); // показує суму цих значень
```

[demo]
Loading