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);
}
// ...
}
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
·
Isn't this essentially describing a singleton pattern? http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#