Home » Javascript » What is wrong with my javascript object?

What is wrong with my javascript object?

Posted by: admin October 29, 2018 Leave a comment

Questions:

I have just started learning OOP in javascript and I am trying to re-write a simple program using OOP that I had previously written as a procedural program. The program is a reaction tester in which a random shape appears on the screen and the user must click it as quickly as possible. After clicking the shape, the time in seconds that it took for the user to respond is displayed.

I have not gotten very far, I am just trying to make a square of random size and random color appear on the screen, but I can’t even manage that. See my code below:

<script type="text/javascript">

function Shape () {
  this.x = Math.floor(Math.random()*850);
  this.y = Math.floor(Math.random()*850);
  this.draw();
}

Shape.prototype.draw = function() {
  var shapeHtml = '<div></div>';
  var widthAndHeight = Math.floor(Math.random()*400);
  var left = Math.floor(Math.random()*850);
  var top = Math.floor(Math.random()*850);
  this.shapeElement = $(shapeHtml);
  this.shapeElement.css({
    position: "relative",
    left: this.left,
    top: this.top,
    width: widthAndHeight,
    height: widthAndHeight,
  });
  $("body").append(this.shapeElement);
}

Shape.prototype.colour = function() {
  var colours = '0123456789ABCDEF'.split('');
  var randomColour = "#";
  for (i = 0; i < 6; i++) {
    randomColour+=colours[Math.floor(Math.random()*16)];
  };
  this.shapeElement.css({backgroundColor: 'randomColour'});
}

var square = new Shape();


</script

So far, no square will appear on the screen. All that happens is a div of a random size is appended, but it is always in the upper-left position and has no background color. The console is not helping me because it is not showing that there are any errors in my code. I am extremely confused and finding the transition to OOP is extremely confusing. Any help in understanding why this won’t work would be extremely appreciated!

Answers: