4

I was going through broccoli plugins and I see this line a lot. What is it used for?

function MyCompiler (arg1, arg2, ...) {
  if (!(this instanceof MyCompiler)) return new MyCompiler(arg1, arg2, ...);
  ...
};
akula1001
  • 4,576
  • 12
  • 43
  • 56
  • 1
    it guards against forgetting "new " when constructing an instance, turning a direct call into a "new " call (which alters _this_ from global to the instance itself). – dandavis Dec 06 '14 at 23:36

1 Answers1

8

That is so that you can use it with or without the new keyword.

E.g.:

var comp = new MyCompiler();

or:

var comp = MyCompiler();

If you call it as a function, it will call itself with the new keyword and return the instance.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005