Created
August 28, 2012 14:55
-
-
Save markstickley/3498737 to your computer and use it in GitHub Desktop.
JS pre-function boilerplate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ClassName = function(){ | |
if(this === window){ | |
throw new Error('ClassName must always be called with the "new" prefix'); | |
} | |
this.status = null; | |
}; |
If this is what you want, why not just use strict mode, which would prevent this from happening (i.e. it throws an error) or just code defensively, i.e.
function ClassName() {
if (this === window) return new ClassName;
this.status = null;
}
This way you can either use your function as a constructor or a factory :).
You can also set up jshint to warn about Constructor functions (capitalised functions) being called without new
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wouldn't it be nice if you could somehow apply lines 2-4 seamlessly to every constructor function?