Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function methods in prototype become undefined

I have planned to get a rid of jQuery, just to learn more plain javascript to build my own libraries. I have created function __ similar to jQuery’s $.
First prototype method I choose to be _addClass which actually add a class to DOM element(s);

Html code is simple:

(() => {
    function __(arg) {
        if (!(this instanceof __))
            return new __(arg);
        this.element = null;
        this.elements = null;
        this.singleElement = false;
        switch (arg.substring(0, 1)) {
            case ".":
                this.elements = document.getElementsByClassName(arg.substring(1));
                break;
            case "#":
                this.element = document.getElementById(arg.substring(1));
                this.singleElement = true;
                break;
            case "&":
                this.elements = document.getElementsByName(arg.substring(1));
                break;
            default:
                this.elements = document.querySelectorAll(arg);
                break;
        }
        return this;
    }

    __.prototype._addClass = (a) => {
        if (this.singleElement) {
            this.element.classList.add(a);
            return this.element;
        } else {
            this.elements.forEach((element) => element.classList.add(a));
            return this.elements;
        }
    }

    document.getElementById("btn").addEventListener("click", () => {
        __("#test")._addClass("new-class-style");
    })
})();
<div id="test">Div content</div>
<button id="btn">Button</button>

However, I’m getting error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught TypeError: Cannot read properties of undefined (reading ‘classList’)

pointing to this.element or this.elements or this.singleElement are undefined and I just can’t figure why?

>Solution :

That’s because you’re using an arrow function for your _addClass method and so the this keyword becomes undefined. Changing it back to normal function fixes the issue:

 (() => {
        function __(arg) {
          if (!(this instanceof __)) return new __(arg);
          this.element = null;
          this.elements = null;
          this.singleElement = false;
          switch (arg.substring(0, 1)) {
            case '.':
              this.elements = document.getElementsByClassName(arg.substring(1));
              break;
            case '#':
              this.element = document.getElementById(arg.substring(1));
              this.singleElement = true;
              break;
            case '&':
              this.elements = document.getElementsByName(arg.substring(1));
              break;
            default:
              this.elements = document.querySelectorAll(arg);
              break;
          }
          return this;
        }

        __.prototype._addClass = function (a) {
          if (this.singleElement) {
            this.element.classList.add(a);
            return this.element;
          } else {
            this.elements.forEach((element) => element.classList.add(a));
            return this.elements;
          }
        };

        document.getElementById('btn').addEventListener('click', () => {
          __('#test')._addClass('new-class-style');
        });
      })();
    <div id="test">Div content</div>
    <button id="btn">Button</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading