It's a bit hacky and I don't really recommend doing this but I understand the reasons for why it's sometimes necessary if you need to integrate with some legacy code or transition your API. Here's one way of doing it.
First, we need a way to detect if our function is called with new or not. Now, depending on weather we're in strict mode or not, if it's not called with new then this will either be undefined or the global object. If it's called with new then it will be an instance of the object inherited from the prototype. So here's how we can check:
function createObj () {
if (typeof this == 'undefined' || typeof this.Array == 'function') {
// Not called with `new`
}
else {
// Called with `new`
}
}
Now using this we can properly construct the object:
function createObj () {
var self; // replacement of `this` because what it points to
// depends on the logic below:
if (typeof this == 'undefined' || typeof this.Array == 'function') {
// Not called with `new`
self = Object.create(createObj.prototype); // create object instance
}
else {
// Called with `new`
self = this;
}
// From this point on do things normally except use `self`
// instead of `this`..
// Remember to return `self` at the end for when we are not
// called with `new`:
return self;
}
Now the function can be used as either a constructor or object factory.
var newObj = {}..? And check forthisinside the function to differentiate.