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.
Written by David Godfrey
Related protips
4 Responses
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);
}
// ...
}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 :)
Perfect, simple and easily implemented on existing code.
Isn't this essentially describing a singleton pattern? http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside