есть вот такой вот код:
class Book {
constructor() {
this.param1 = 1;
this.param2 = [];
this.param3 = this.summ();
}
summ() {
console.log(`summ started`);
let a = 0;
this.param2.forEach((obj) => {
a += obj.val
});
return a
}
addArray(obj) {
this.param2.push(obj)
}
}
let arr = [{
val: 1
}, {
val: 2
}, {
val: 3
}, ];
let book = new Book();
book.addArray(arr);
console.log(book.param3);
Не могу понять, из-за чего, третий параметр - ndefined... В случае, если метод возвращает сумму значений параметров - все ок... Как забороть ?
Потому что param3 вычисляется здесь:
let book = new Book();
и не обновляется после вызова
book.addArray(arr);
addArray(obj) {
obj.forEach(el => this.param2.push(el));
this.param3 = this.summ();
}
class Book {
constructor() {
this.param1 = 1;
this.param2 = [];
this.param3 = this.summ();
}
summ() {
console.log(`summ started`);
let a = 0;
this.param2.forEach((obj) => {
a += obj.val
});
return a
}
addArray(obj) {
obj.forEach(el => this.param2.push(el));
this.param3 = this.summ();
}
}
let arr = [
{ val: 1 },
{ val: 2 },
{ val: 3 }
];
let book = new Book();
book.addArray(arr);
console.log(book.param3);
Реализуйте поле через getter:
class Book {
constructor() {
this.param1 = 1;
this.param2 = [];
}
get param3() {
console.log(`summ started`);
let result = this.param2.reduce((acc, cur) => acc += cur.val, 0);
return result;
}
addArray(obj) {
this.param2.push(...obj);
}
}
let arr = [{
val: 1
}, {
val: 2
}, {
val: 3
}];
let book = new Book();
book.addArray(arr);
console.log(book.param3);
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости