Possible Duplicate:
How to detect if a function is called as constructor?
I would like to have a function in JavaScript which behaves differently if it's called normally or if it's invoked in order to create a new instance. There could be many different uses, where the two functionalities can be related or not related. One use would be to exempt the coder from having to type new
, when the function is always used to create new instances:
function MyClass(arg1, arg2) {
if(/* not called with "new" */) return new MyClass(arg1, arg2);
// instance initialization stuff here...
}
This way I wouldn't have to type var x = new MyClass(arg1, arg2)
: it would be enough to type var x = MyClass(arg1, arg2)
(but the former wouldn't be wrong either).
Just one example of a possible use.
Can this be done? If so, how?