Hacker News new | ask | show | jobs
by couchand 2998 days ago
It's purely syntactic sugar. You can even get the new protection yourself:

    function Cat() {
      if (!(this instanceof Cat)) {
        throw new Error("please use new!");
      }
    }
or, if you want to be a bit nicer to your users:

    function Cat() {
      if (!(this instanceof Cat)) {
        return new Cat();
      }
    }
1 comments

Seems like the 2nd option might prevent me from using Cat's as a mixin
Mixins have terrible performance characteristics and lead to fragile code. While they were huge a few years ago, most new frameworks either avoid them or (in cases like React) chose to remove them for these reasons. In an existing codebase, that matters a lot. In newer codebases (or newer parts of existing ones) it shouldn't matter that much at all.
Both options will break mixins.

  function CatDog () {
     Cat.apply(this, arguments);
  }

  CatDog.prototype = Object.assign(Dog.prototype, Cat.prototype);
In the above example, CatDog is not an instance of Cat, since it never actually inherits from the Cat prototype.
Mixins in ES6 should be functions taking a class and returning another class that extends it:

https://alligator.io/js/class-composition/