Given a function:
function x(arg) { return 30; }
You can call it two ways:
result = x(4);
result = new x(4);
The first returns 30, the second returns an object.
How can you detect which way the function was called inside the function itself?
Whatever your solution is, it must work with the following invocation as well:
var Z = new x();
Z.lolol = x;
Z.lolol();
All the solutions currently think the Z.lolol() is calling it as a constructor.
NOTE: This is now possible in ES2015 and later. See Daniel Weiner’s answer.
I don’t think what you want is possible [prior to ES2015]. There simply isn’t enough information available within the function to make a reliable inference.
Looking at the ECMAScript 3rd edition spec, the steps taken when
new x()is called are essentially:xxas normal, passing it the new object asthisxreturned an object, return it, otherwise return the new objectNothing useful about how the function was called is made available to the executing code, so the only thing it’s possible to test inside
xis thethisvalue, which is what all the answers here are doing. As you’ve observed, a new instance of*xwhen callingxas a constructor is indistinguishable from a pre-existing instance ofxpassed asthiswhen callingxas a function, unless you assign a property to every new object created byxas it is constructed:Obviously this is not ideal, since you now have an extra useless property on every object constructed by
xthat could be overwritten, but I think it’s the best you can do.(*) “instance of” is an inaccurate term but is close enough, and more concise than “object that has been created by calling
xas a constructor”