Object

View My GitHub Profile

Object Creation

Factory Pattern:

function a(){
    var obj = {
        b : "Hi! ",
        c : "Bye!"
    };
    return obj;
}

var z = a();                             //i.e z = obj
console.log(z.b, z.c);                   // Hi! Bye!

z.constructor === Object;                // true
z instanceof Object;                    // obvious: every object is instance of Object

z.constructor === obj;
//ReferenceError: 'obj' is undefined because its defined inside 'a'  

z instanceof obj;                         
// ReferenceError: 'obj' is undefined because its defined inside 'a'
//The problem now is we can't tell which specific object z belongs to.

Disadvantage:

It becomes difficult to query for the origin specific object. This can be overcomed by Constructor Pattern

Constructor Pattern:

function A(){
    this.b = "Hi! ";
    this.c = "Bye!";
    this.show = function(){
        console.log(z.b,z.c);
    };
};

var z = new A();
z.show();
z instanceof A;           //true
z instanceof Object;      //true
A instanceof Object;      //true

var x = new A();
x.show();

Disadvantage:

Here z and x both have their own copy of show() method as this is used i.e. it is not shared hence takes up memory. This can be overcomed by Prototype Pattern.

Prototype Pattern:

function A(){
}
A.prototype = {
    constructor: A,    
    /*Here creating the prototype object overrides the inherited prototype so constructor is made to point to A*/
    b : "Hi! ",
    c : "Bye!",
    d : ["Hi","there!"],
    show : function(){
    console.log(this.b,this.c);
    }
}

var z = new A();
var x = new A();
x.d;                  //before change: ["Hi","there!"]
z.show();             
z.d.push("Soumen"); 
x.d;                  //after change: ["Hi","there!","Soumen"]

Disadvantage:

Here since prototype is used everything in A is shared among its instances. So changing array d through z causes d to change for all instances. This can be overcomed by using both constructor pattern for individual properties as well as prototype pattern for methods.