Задача Яндекс Практикума, class, this. Помогите разобраться
class Transport {
constructor(type, price, vendor, model) {
this.type = type;
this.price = price;
this.vendor = vendor;
this.model = model;
}
getInfo() {
return `${this.vendor}, ${this.model}`;
}
getPrice() {
return this.price.toLocaleString('ru-RU') + ' ₽';
}
}
class Car extends Transport {
constructor(vendor, model, doorsCount, price) {
super('car', price, vendor, model);
this.doorsCount = doorsCount;
}
getDoorsCount() {
return `Кол-во дверей: ${this.doorsCount}`;
}
}
class Bike extends Transport {
constructor(vendor, model, maxSpeed, price) {
super('bike', price, vendor, model);
this.maxSpeed = maxSpeed;
}
getMaxSpeed() {
return `Макс. скорость: ${this.maxSpeed} км/ч`;
}
}
"Вы устроились разработчиком в автомобильную компанию. Первое задание — починить код, который отвечает за отображение информации о транспорте и цене. Поправьте классы так, чтобы ошибка TypeError: Cannot read property 'vendor' of undefined больше не отображалась. Вносите изменения только в файл task.js."
Данную задачу я уже сутки пытаюсь решить, как я заметил при обработке проверки запускается другой скрипт и он начинает вызывать функции из классов передавая туда значения. Когда он создаёт new Car и делает вызов getDoorsCount, все параметры пролетают нормально. А вот при вызове родительского getInfo, все переменные становятся undefind, я прочитал всё что только мог и не могу понять в чём конкретно проблема, почему переменные не передаются при вызове родительской функции.
Модулятор яндекса даёт подсказку что нужно привязать контекст у getinfo и использовать ключевое слово this. Но что-то это не даёт ясности.
Проверка запускает такой код
const catalog = document.querySelector('.page__catalog');
const tpl = (img, title, info, price) => {
return `
<img src="${img}" alt="" class="card__image" />
<div class="card__description">
<h2 class="card__title">${title}</h2>
<p class="card__info">
${info}
</p>
<p class="card__price">${price}</p>
</div>
`;
};
for (const item of data) {
const entityContainer = document.createElement('article');
entityContainer.classList.add('card', 'catalog__item');
if (item.type === 'car') {
const { getDoorsCount, getInfo, getPrice } = new Car(
item.vendor,
item.model,
item.doorsCount,
item.price
);
entityContainer.innerHTML = tpl(item.img, getInfo(), getDoorsCount(), getPrice());
} else {
const { getMaxSpeed, getInfo, getPrice } = new Bike(
item.vendor,
item.model,
item.maxSpeed,
item.price
);
entityContainer.innerHTML = tpl(item.img, getInfo(), getMaxSpeed(), getPrice());
}
catalog.appendChild(entityContainer);
}
Ответы (3 шт):
написано же привяжи контекст в конструкторе car пропиши this.getInfo= this.getInfo.bind(this)
Рабочий код:
class Transport {
constructor(type, price, vendor, model) {
this.type = type;
this.price = price;
this.vendor = vendor;
this.model = model;
}
getInfo() {
return `${this.vendor}, ${this.model}`;
}
getPrice() {
return this.price.toLocaleString('ru-RU') + ' ₽';
}
}
class Car extends Transport {
constructor(vendor, model, doorsCount, price) {
super('car', price, vendor, model);
this.doorsCount = doorsCount;
}
getInfo = this.getInfo.bind(this);
getPrice = this.getPrice.bind(this);
getDoorsCount = this.getDoorsCount.bind(this);
getDoorsCount() {
return `Кол-во дверей: ${this.doorsCount}`;
}
}
class Bike extends Transport {
constructor(vendor, model, maxSpeed, price) {
super('bike', price, vendor, model);
this.maxSpeed = maxSpeed;
}
getInfo = this.getInfo.bind(this);
getPrice = this.getPrice.bind(this);
getMaxSpeed = this.getMaxSpeed.bind(this);
getMaxSpeed() {
return `Макс. скорость: ${this.maxSpeed} км/ч`;
}
}
Так же можно сделать стрелочные функции
class Transport {
constructor(type, price, vendor, model) {
this.type = type;
this.price = price;
this.vendor = vendor;
this.model = model;
}
getInfo = () => {
return `${this.vendor}, ${this.model}`;
}
getPrice = () => {
return this.price.toLocaleString('ru-RU') + ' ₽';
}
}
class Car extends Transport {
constructor(vendor, model, doorsCount, price) {
super('car', price, vendor, model);
this.doorsCount = doorsCount;
}
getDoorsCount = () => {
return `Кол-во дверей: ${this.doorsCount}`;
}
}
class Bike extends Transport {
constructor(vendor, model, maxSpeed, price) {
super('bike', price, vendor, model);
this.maxSpeed = maxSpeed;
}
getMaxSpeed = () => {
return `Макс. скорость: ${this.maxSpeed} км/ч`;
}
}