3

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?

1
  • Maybe try with singletons and make the constructor private if you want it not to be called as a function? Commented Sep 10, 2013 at 10:40

3 Answers 3

2

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();
    }

    ...
};
Sign up to request clarification or add additional context in comments.

Comments

1
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().

Comments

0

How about this:

/*WARNING CALL THIS ONLY AS A CONSTRUCTOR, NOT AS A FUNCTION*/

3 Comments

Don't be so fatuous to assume every user would read (and follow) such docs :-)
I'm being somewhat sarcastic, but at the same time, cars don't prevent you from driving without oil in the engine. You are supposed to know to use the car correctly, or read the docs to find out how to do so.
JSDoc format: /** <newline> * @constructor <newline> */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.