From Secrets of the Javascript Ninja (great walkthrough btw):
// We need to make sure that the new operator is always used
function User(first, last){
if ( !(this instanceof User) )
return new User(first, last);
this.name = first + " " + last;
}
var name = "Resig";
var user = User("John", name);
assert( user, "This was defined correctly, even if it was by mistake." );
assert( name == "Resig", "The right name was maintained." );
Do any real-world code style guides make all constructors do this kind of safeguarding (the first two lines)? I believe linters will catch calls like User("John", "Resig") and warn about the missing new, won’t they?
I recommend you use strict mode and test in a browser that supports it. For example,
this will throw in strict mode if you neglect the
new. For example,will throw a
TypeErrorin Firefox. This allows you to catch errors without having to pay the penalty of aninstanceofcheck. It throws a type error even if you call it outside of strict mode. This is because directly invoked strict mode funcitons havethisbound toundefinedinstead of global. Setting a property onundefinedresults in aTypeErrorexception.