zzzfairy
@zzzfairy
Учусь на front-end разработчика

Почему не передаются аргументы через this?

Только учусь. Не могу понять, что пошло не так в уроке.
Через this не передаются аргументы (если их записать сразу в cssText, то код работает).

"Создать класс options:
Он должен содержать свойства: height, width, bg, fontSize, textAlign.
Он должен содержать метод, создающий новый div на странице, записывающий в него любой текст и при помощи cssText изменять свой стиль из переданных параметров.
Создать новый объект через класс.
Вызвать его метод и получить элемент на странице."

"use strict";
class Options {
         constructor(height, width, backgroundColor, fontSize, textAlign) {
             this.height = height;
             this.width = width;
             this.backgroundColor = backgroundColor;
             this.fontSize = fontSize;
             this.textAlign = textAlign;
         }
         makeNewDiv() {
            var newDiv = document.createElement('div');
            document.body.appendChild(newDiv);
            newDiv.textContent = prompt("What?", "");
            newDiv.style.cssText = 'height: this.height; \
            width: this.width; \
            background-color: this.backgroundColor; \
            font-size: this.fontSize; \
            text-align: this.textAlign';      
         }

     }
     var newOptions = new Options(100, 100, red, 44, center);
    
    console.log(newOptions.makeNewDiv);
  • Вопрос задан
  • 290 просмотров
Решения вопроса 1
Vlad_IT
@Vlad_IT Куратор тега JavaScript
Front-end разработчик
Вот это вот
newDiv.style.cssText = 'height: this.height; \
            width: this.width; \
            background-color: this.backgroundColor; \
            font-size: this.fontSize; \
            text-align: this.textAlign';

на выходе будет вот этим вот
height: this.height;
width: this.width;
background-color: this.backgroundColor;
font-size: this.fontSize;
text-align: this.textAlign


Вы не передаете значения переменных (height, fontSize и.т.д.), и просто вставляете название переменной в строку. Нужно либо так
newDiv.style.cssText = `height: ${this.height}; 
            width: ${this.width}; 
            background-color: ${this.backgroundColor}; 
            font-size: ${this.fontSize}; 
            text-align: ${this.textAlign}`;

либо так

newDiv.style.cssText = 'height: ' + this.height + '; \
            width: ' + this.width + '; \
            background-color: ' + this.backgroundColor + '; \
            font-size: ' + this.fontSize + '; \
            text-align: ' + this.textAlign;
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
01 мая 2024, в 02:11
5000 руб./за проект
01 мая 2024, в 00:29
2000 руб./за проект
01 мая 2024, в 00:20
15000 руб./за проект