JavaScript Series - Part 2 - 10 Exercise Prototypical Inheritance

This one was tough, I didn’t even complete the whole exercise the part that stumped me was making the optional constructor parameter for ```HtmlSelectElement(optionalParamater). According to the video Basically, you can call the constructor and enter in an array of elements and said array of elements would === this.items if the constructor parameter isn’t an array of elements and instead is any other value then that would be pushed into this.items.

Anyways, here is what I managed to do myself and its time to watch his solution cause to be frank took way to long trying to figure this out myself :joy:

    // Exserise Part 1
    function HtmlElement(){
      this.click = function(){
        console.log("Click");
      }
    };

    HtmlElement.prototype.focus = function(){
      console.log("Focus");
    }

    const h = new HtmlElement();
    console.log(h);

    // Exsersise Part 2

    function HtmlSelectElement(){
      this.items = [],

      this.addItem = function(item){
        this.items.push(item);
      },
      this.removeItem = function(item){
        const otherWords = this.items.filter(word => word !== item)
        this.items = otherWords;
      }
    };

     // I don't understand how to make an opitional contructor parameter
     // I thought it would be Object.defineProporty(this, 'HtmlSelectElement' { :set})
     // I tried that but it didn't work so not sure what to do...
     // I managed to get the addItem and removeItem methods to work though but, 
     // just missing the constructor parameter

    HtmlSelectElement.prototype = HtmlElement;
    const hs = new HtmlSelectElement();
    console.log(hs);

Update: Just watched his solution and yeah most of mine was correct aside from the inheritance and the constructor parameter but, he mentioned this is an old way to do things and in es6 it gets easier haha that makes me happy cause this way is hella confusing.

1 Like