Skip to content

Instantly share code, notes, and snippets.

@mnaamani
Last active August 29, 2015 14:24
Show Gist options
  • Save mnaamani/a119ead24a4c674271a4 to your computer and use it in GitHub Desktop.
Save mnaamani/a119ead24a4c674271a4 to your computer and use it in GitHub Desktop.
//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