‘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:
bennadel.com/blog/2522-providing-a-return-v..