Last active
September 26, 2015 08:08
-
-
Save eliperelman/1066535 to your computer and use it in GitHub Desktop.
Guaranteed Instances
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 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