Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a constructor?

Tags:

javascript

oop

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?

like image 997
Deqing Avatar asked Feb 14 '26 15:02

Deqing


2 Answers

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

    ...
};
like image 114
Alnitak Avatar answered Feb 17 '26 05:02

Alnitak


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

like image 32
Bergi Avatar answered Feb 17 '26 04:02

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!