Here is a list of few different styles mostly used by developers to create objects.
- Object constructor
var person = new Object(); person.name = "Mark", person.getName = function(){ return this.name ; };
- Literal constructor
var person = { name : "Mark", getName : function (){ return this.name } }
- Function based
function Person(name){ this.name = name this.getName = function(){ return this.name } }
- prototype based
function Person(){}; Person.prototype.name = "Mark";
- Function and prototype based
function Person(name){ this.name = name; } Person.prototype.getName = function(){ return this.name }
- Singleton based
var person = new function(){ this.name = "Mark" }
Out of those styles function based style and singleton based style are the most used and sufficient for most of simple implementations.
Lets see some of usages of those two styles.
- Function Based
This style is used when more objects are need to be created of a type.function Person(name){ this.name = name this.getName = function(){ return this.name } }
Ex:var person1= new Person("Ann"); var person2= new Person("Jhon"); var person3= new Person("Steven");
Here "Person" is called the constructor function. This is similar to classes in other OO languages.
- Singleton based
This style is used if you only need one object of a kind.var person = new function(){ this.name = "Mark" }
No comments:
Post a Comment