While looking at some source code I found this:
require["./helpers"] = new function() {...};
Why is new being used here? When I run this on JSLint I get
Weird construction. Delete 'new'.
So is this just a form of style, personal preference? Or is there something behind this?
It’s a way of creating an object which allows
thisto be used during the creation.This offers some direct reference to the object during instantiation that object literal syntax does not allow.
The object literal version would need to look like this:
So the anonymous function is basically used as a temporary constructor. We could just as easily use a named constructor function, but since we don’t really care about the constructor, we just use a “disposable” one.
And of course since it’s a function, it creates a local variable scope, so if you assign any functions to the new object, they will be able to close over local variables.