Javascript

‘return’ inside constructors

function Eg() {
  this.name = 10;
  return 'adarsh';
}

new Eg(); // Returns {name: 10}

However, if you return a object inside a constructor function, that object will be returned.

function Eg() {
  this.name = 10;
  return { 
    name: 'adarsh' 
  };
}

new Eg(); // Returns {name: "adarsh"}

So basically, whenever you return a primitive inside a constructor function, that is ignored. However any reference types returned inside a constructor function will override the ‘new’ly created object.

A sample ‘new’ implementation

NEW = function(constructor, args){
    // var obj = Object.create(constructor.prototype);
    var obj = {};
    obj.__proto__ = constructor.prototype;
    var retValue = constructor.apply(obj, args);
    if(typeof retValue === 'object') {
        return retValue;
    }
    else {
        return obj;
    }
};

Usage: NEW(Person, ['Adarsh']);

Note: Line 1 (commented) inside the above function 
      can replace lines 2 and 3

For more details, follow the below link:
http://www.bennadel.com/blog/2522-providing-a-return-value-in-a-javascript-constructor.htm

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s