Created
May 30, 2012 08:47
-
-
Save erikhazzard/2834632 to your computer and use it in GitHub Desktop.
javascript object creation
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
//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