Skip to content

Instantly share code, notes, and snippets.

@eliperelman
Last active September 26, 2015 08:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliperelman/1066535 to your computer and use it in GitHub Desktop.
Save eliperelman/1066535 to your computer and use it in GitHub Desktop.
Guaranteed Instances
var Car = function(make, model, color) {
this.make = make;
this.model = model;
this.color = color;
};
// This way works:
var pinto = new Car('ford', 'pinto', 'green');
// but this doesn't:
var pinto = Car('ford', 'pinto', 'green');
// Possible Solution:
var Car = function(make, model, color) {
if (!(this instanceof Car)) {
return new Car(make, model, color);
}
this.make = make;
this.model = model;
this.color = color;
};
// Sometimes I like to write it this way:
var Car = function fn(make, model, color) {
if (!(this instanceof fn)) {
return new fn(make, model, color);
}
this.make = make;
this.model = model;
this.color = color;
};
// Now both ways work:
var pinto = new Car('ford', 'pinto', 'green');
var pinto = Car('ford', 'pinto', 'green');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment