1

If I have a simple component such as the one below, would it better to use static methods within my class or not? I realise this could be down to opinion but what I'm interested in is if there are architectural reasons why one way might have advantages over the other.

Non static methods:

class mainNav {
  toggleMainNav() {
    const navBtn = document.getElementById('toggle-menu');
    const navMenu = document.getElementById('main-nav');

    navBtn.addEventListener('click', () => {
      navMenu.classList.toggle('open');
    });
  }

  init() {
    this.toggleMainNav();
  }
}

module.exports = mainNav;

To instantiate I would need to instantiate the class first like so:

const mainNav = require("../js/components/mainNav/mainNav");

//Init nav
const nav = new mainNav;
nav.init();

Alternatively with static methods I could do this:

class mainNav {
  static toggleMainNav() {
    const navBtn = document.getElementById('toggle-menu');
    const navMenu = document.getElementById('main-nav');

    navBtn.addEventListener('click', () => {
      navMenu.classList.toggle('open');
    });
  }

  static init() {
    this.toggleMainNav();
  }
}

module.exports = mainNav;

and instantiate:

const mainNav = require("../js/components/mainNav/mainNav");

mainNav.init();

On the face of it using static methods in this case seems easier as I don't have to instantiate an instance of the class first.

Not coming from an OOP programming background, Is there is a reason why doing this would be considered bad practise?

Antfish
  • 1,313
  • 2
  • 22
  • 41
  • 1
    Yes. You should [not have a `class` with only static methods](https://stackoverflow.com/a/29895235/1048572). You also should not have an instance with no state and no data. In fact, it looks like all you need is a plain function. – Bergi Feb 17 '18 at 17:03
  • static methods cannot use `this` when not called with an object. It will just be undefined – Agney Feb 17 '18 at 17:04
  • @BoyWithSilverWings Of course that's a "problem" that all methods and functions have, not just static ones – Bergi Feb 17 '18 at 18:02

1 Answers1

2

A class with no data is basically a collection of static methods. This is an antipattern. In this case, just exporting the function alone would suffice, like this:

function doSomething() { ... }
module.exports = doSomething

and use it like this:

const func = require('../path/module')
func()
Mario F
  • 45,569
  • 6
  • 37
  • 38