I need a constructor that shouldn't be called as a function:
function Foo() {
...
};
var f = new Foo(); // ok
Foo(); // throws error
Searched in here and found that maybe I can use following to check if it is called as a function
if (!(this instanceof arguments.callee))
If so then what error should I throw?
And, is there any better way to define a constructor?
arguments.callee is (unfortunately, IMHO) deprecated in ES5 strict mode.
Instead of throwing an error, I recommend that you instantiate the object instead if the caller forgets to use new:
function Foo() {
if (!(this instanceof Foo)) {
return new Foo();
}
...
};
if (!(this instanceof arguments.callee))
arguments.callee is deprecated. Just use the proper reference: this instanceof Foo.
If so then what error should I throw?
Just a normal error indicating the reason:
throw new Error("Foo must be called as a constructor");
Btw, you might as well tolerate it and create a new instance nonetheless: return new Foo().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With