Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active February 20, 2024 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansmith/0facbefe28e0a309cc363d0d7c2c0ad5 to your computer and use it in GitHub Desktop.
Save nathansmith/0facbefe28e0a309cc363d0d7c2c0ad5 to your computer and use it in GitHub Desktop.
Example of how NOT to build a JavaScript class.

JS class footgun

I came across some code awhile ago that, though I can't share exactly, I wanted to document as a "footgun."

You should never have a class that can be used both as a singleton with helper methods and can be instantiated.

Even if you did, there should never be static and public methods — by the same name — that do different things.

/*
  This is a pseudo coded version of
  a bad JavaScript `class` I noticed.

  I thought it'd be funny to document.
*/

class Robot {
  // Available directly.
  static helpHumans() {
    console.log('I help humans!');
  }

  // Available via `new`.
  helpHumans() {
    console.log('I kill humans!');
  }
}

const myRobot1 = Robot;
const myRobot2 = new Robot();

// Logs: "I help humans!"
console.log(
  myRobot1.helpHumans()
);

// Logs: "I kill humans!"
console.log(
  myRobot2.helpHumans()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment