Last active
August 29, 2015 14:24
-
-
Save mnaamani/a119ead24a4c674271a4 to your computer and use it in GitHub Desktop.
This file contains 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
//pseudo-classical | |
function Car(options) { | |
//if new keyword was used to invoke the constructor | |
//`this` would be an instance of Car. | |
if (!(this instanceof Car)) { | |
//ensure constructor is called with new keyword | |
return new Car(options) | |
} | |
this.instanceMethod = function(){}; | |
} | |
Car.prototype.sharedMethod = function(){}; | |
//functional | |
var Vehicle = function() { | |
var instance = {}; | |
instance.instanceMethod = function(){}; | |
return instance; | |
} | |
//normally Car should be instantiated with `new` | |
var myCar = new Car(); | |
//...but our check in the constructor averts the problem if we forget to do so. | |
//so we can invoke it directly and get expected result | |
var myCar = Car(); | |
//Vehicle doesn't need to be instantiated with new, but will still work | |
var myVehicle = new Vehicle(); | |
//so as a naming convention all classes can be capitalised even if you don't use new keyword. | |
//if you want to clearly indicate that a function doesn't need new keyword it could be given an name like: | |
var makeVehicle = function(){ | |
var instance = {}; | |
instance.instanceMethod = function(){}; | |
return instance; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment