0

I'm getting this error message when i run this code : index.js:19 Uncaught TypeError: this.getRandomColor is not a function at setUp (index.js:19)

I used this. to refer to the getRandomColor method but it doesn't work. Can't figure out why.

class Renderer {
constructor() {
    this.setUpAfterDelay();
}
setUp() {

    let width = Math.random() * 300;
    let height = Math.random() * 300;
    let top = Math.random() * 200;
    let left = Math.random() * 200;


    let shape = document.createElement("div");
    shape.style.width = width + "px";
    shape.style.height = height + "px";
    shape.style.position = "absolute";
    shape.style.top = top + "px";
    shape.style.left = left + "px";
    shape.style.backgroundColor = this.getRandomColor();
    document.body.appendChild(shape);

}
setUpAfterDelay() {
    setTimeout(this.setUp, Math.random() * 2000);

}

getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
}

let renderer = new Renderer;
Graham
  • 6,577
  • 17
  • 55
  • 76
Marburc
  • 37
  • 4
  • 1
    The global class scope is not known the moment you call the getRandomColor() function. Try to bind your function to this in the constructor by calling this.setup.bind(this). Not sure if it solves your issue, but worth a try. – Jonathan Stellwag Oct 30 '18 at 13:47
  • im not sure how u run this but it seems like you try to get the output of an function(getRandomColor) before that function is running – Ramon de Vries Oct 30 '18 at 13:53
  • Or just transform the method into arrow functions. – joseatchang Oct 30 '18 at 13:53

0 Answers0