David G
David G

Reputation: 96845

Why is new being used with a function expression?

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?

Upvotes: 3

Views: 101

Answers (2)

LetterEh
LetterEh

Reputation: 26706

It's basically doing the same thing as an IIFE which returns a public interface (an object with public properties/methods which have access to the private scope of the function) of some sort, except for people who REALLY AND DESPERATELY want to use this during the construction, and can't be bothered to use call, bind or apply, or just flat out return a regular inline object.

Under the hood there are a few difference between IIFEs and constructor-functions when both are used in their anticipated ways... ...but in this instance, there really isn't anything inherently different about the final return value done either way, from a high-level (ie: as far as your program should be concerned).

Upvotes: 0

I Hate Lazy
I Hate Lazy

Reputation: 48789

It's a way of creating an object which allows this to be used during the creation.

This offers some direct reference to the object during instantiation that object literal syntax does not allow.

var o = new function() {
    this.num = Math.random();
    this.isLow = this.num < .5; // you couldn't reference num with literal syntax
};

The object literal version would need to look like this:

var o = {
    num: Math.random()
};
o.isLow = o.num < .5;

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.

Upvotes: 6

Related Questions