Last Updated: September 09, 2019
·
1.037K
· reactiveraven

Prevent object constructor being run as function

function Foo() {
    if (! (this instanceof Foo)) {
        throw "Attempted to call a constructor as a function. " + 
            "Must use 'new' eg 'new Foo()'.";
    }
    // ...
}

Gives an explanation on console and stops unintended behaviour before it happens.

4 Responses
Add your response

Great point. How about warning and redirecting to new Foo() instead of throwing an exception?

function Foo() {
  // verify the new operator was used to
  // ensure 'this' works as expected
  if (false === (this instanceof Foo)) {
      console.warn('Foo() invoked as a function;',
                   'use `new Foo()` instead');
      return new Foo(arguments);
  }
    // ...
}
over 1 year ago ·

Good idea. I'm building new things at the moment, so I wanted other coders to know if they're doing something wrong before it can become a bug later, but if you're adding into existing code it'd make sense to be a warning rather than crash the entire suite. Thanks :)

over 1 year ago ·

Perfect, simple and easily implemented on existing code.

over 1 year ago ·
over 1 year ago ·