nunruw
Last Updated: February 25, 2016
·
864
· 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

12690

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 ·
12716

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 ·
12743

Perfect, simple and easily implemented on existing code.

over 1 year ago ·
16091
over 1 year ago ·