javascriptobject-construction

How to make an object constructor in JavaScript;


Could you please explain me what's wrong in the following code?

function box (width, height, color) {
    this.width=width;
    this.height=height;
    this.color=color;
    this.style.width=width;
    this.style.height=height;
    this.style.backgroundColor=color;
}

var box1 = new box (100, 100, 'red');

document.body.appendChild(box1);

Solution

  • You need to createElement and pass it the parameters as follows:

    function box (width, height, color) {
      this.element = document.createElement('div');
      this.element.style.width=width+'px';
      this.element.style.height=height+'px';
      this.element.style.backgroundColor=color;
      return this.element;
    }
    
    var box1 = box (100, 100, 'red');
    
    document.body.appendChild(box1);