Search code examples
javascriptprototype

Using prototypes to gain more performance


Say I have 100 boxes that inherit the same properties from this constructor:

const Box = function() {

    this.element = document.createElement("div");
    this.painted = false;

    this.init = function() {

        this.element.className = "box";

        this.element.addEventListener("mouseover", () => {
            console.log("you are touching this box!");
            this.change_color("red");
            this.painted = true;
        });
    }

    this.change_color = (color) => this.element.style.background = color;

}

Now, as I understand, there is no way I can use Prototypes in the .addEventListener because each box needs its listener. But what about the function this.change_color? Does each box really need to have this function? Can I make a prototype out of it? (I am guessing not because it uses the box's element, which is a local variable, am I correct?)

Or, let's say I want to make a function that colors all the boxes in my page. How would you go about making a Prototype to do so?


Solution

  • Within a prototype function you can simply use this which will refer to the actual instance of a Box class that you created. Thus you can create a prototype for both the init and change_color function, like so:

    const Box = function(boxName) {
        this.element = document.createElement("div");
        this.painted = false;
        this.myname = boxName;
    }
    
    Box.prototype.init = function() {
      this.element.className = "box";
      this.element.innerText = this.myname;
    
      this.element.addEventListener("mouseover", () => {
        // console.log("you are touching this box!");
        this.change_color("red");
        this.painted = true;
      });
      
      this.element.addEventListener("mouseleave", () => {
        this.change_color("green");
        this.painted = true;
      });
    }
    
    Box.prototype.change_color = function(color) {
      this.element.style.background = color;
    }
    
    const box1 = new Box('box1');
    box1.init();
    
    const box2 = new Box('box2');
    box2.init();
    
    document.body.append(box1.element);
    document.body.append(box2.element);
    .box {
      height: 50px;
      width: 50px;
      border: 1px solid blue;
    }