D
D
Dubolom Unicellular2020-04-22 16:29:18
JavaScript
Dubolom Unicellular, 2020-04-22 16:29:18

Why is the js class not working?

I created a class that should remember the width and height values, and then using the geo() function, write in the console the width and height that I set to the class:

class Canv {
  constructor(width, height) {
    this.width = width.width;
    this.height = height.height;
  }
  
  geometry() {
    console.log(this.width, this.height);
  }
}

const canv = new Canv({
  width: 50, // Задаю классу значение width
  height: 50 // Задаю классу значение height
});
canv.geometry(); // Должно вернуть: 50, 50

But it writes in the browser console: Uncaught TypeError: Cannot read property 'height' of undefined.
Moreover, the error occurs not when the function is called, but when I set the value this.height = height.height in the constructor;
I can't figure out what to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2020-04-22
@duboloms

constructor(width, height) // принимает два значения

const canv = new Canv({ //  посылаешь объект, зачем
  width: 50
  height: 50
});

///////////

class Canv {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  
  geometry() {
    console.log(this.width, this.height);
  }
}

const canv = new Canv(50, 50);
canv.geometry(); // Должно вернуть: 50, 50

D
drawnofmymind, 2020-04-22
@drawnofmymind

And in the constructor, you can pass default parameters like:
constructor(width = {}, height = {})
?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question