Skip to content

Instantly share code, notes, and snippets.

@erikhazzard
Created May 30, 2012 08:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erikhazzard/2834632 to your computer and use it in GitHub Desktop.
Save erikhazzard/2834632 to your computer and use it in GitHub Desktop.
javascript object creation
//The top level function we'll use to create objects from
// (will basically act as a factory for object creation
var createObjects = function(){};
//Define the create function. It's not defined inside the function
// so we don't need to call it to access it. i.e., if this was
// inside createObjects, we'd need to do createObjects().create
createObjects.create = function(name){
//newObject will reference the created object
var newObject = new createObjects[name]();
return newObject;
};
//We can also specify a prototype that all items can share
// (if we assign the prototype to each createObjects.ClassName)
createObjects.prototype.speak = function(){
console.log("My name is " + this.name);
};
createObjects.Person = function(){
this.name = 'Adam';
};
//Note: you could set the prototy of this function
// to equal the createObjects.prototype if you wanted inheritence
createObjects.Person.prototype = createObjects.prototype;
//---------------------------------------
//We can create a 'Person' object using createObjects.create()
person = createObjects.create('Person');
//and log it outputs:
// >createPerson.Peron
console.log(person);
console.log(person.speak())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment