Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save markstickley/3498737 to your computer and use it in GitHub Desktop.
Save markstickley/3498737 to your computer and use it in GitHub Desktop.
JS pre-function boilerplate
var ClassName = function(){
if(this === window){
throw new Error('ClassName must always be called with the "new" prefix');
}
this.status = null;
};
@markstickley
Copy link
Author

Wouldn't it be nice if you could somehow apply lines 2-4 seamlessly to every constructor function?

@gillesruppert
Copy link

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