Creating objects for your design pattern in JavaScript

There are few different ways of creating objects in JavaScript and different ways of using those objects. Most of the beginners in JavaScript are confused with those different ways of handling objects.

Here is a list of few different styles mostly used by developers to create objects.
  1. Object constructor
    
    var person = new Object();
    
    person.name = "Mark",
    person.getName = function(){
      return this.name ; 
    };
    

  2. Literal constructor
    
    var person = { 
      name : "Mark",
      getName : function (){
       return this.name
      } 
    }
    

  3. Function based
    
    function Person(name){
      this.name = name
      this.getName = function(){
        return this.name
      } 
    } 
    

  4. prototype based
    
    function Person(){};
    
    Person.prototype.name = "Mark";
    

  5. Function and prototype based
    
    function Person(name){
      this.name = name;
    } 
    Person.prototype.getName = function(){
      return this.name
    } 
    

  6. 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
    
    function Person(name){
      this.name = name
      this.getName = function(){
        return this.name
      } 
    } 
    
    This style is used when more objects are need to be created of a type.
    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
    
    var person = new function(){
      this.name = "Mark"
    } 
    
    This style is used if you only need one object of a kind.


No comments:

Post a Comment