Sanandrea
Sanandrea

Reputation: 2194

what does function () {} mean when assigned to a variable

I know that functions are objects in javascript, and that functions can be assigned to variables. I am also aware of this question: How does the (function() {})() construct work and why do people use it?.

But I would like to know precisely what does it mean in this context: https://github.com/zsolt/retwis-nodejs/blob/master/domain.js#L43

User = function(){}

This line is followed by the declaration of some member functions (methods?) of the "supposed" User object. It seems there is no other explanation answer here in SO.

Upvotes: 6

Views: 135

Answers (2)

Thevs
Thevs

Reputation: 3253

The canonical way to create an object in Javascript is:

function user(config) { this.config = config; ... } User = new user(config);

It uses this context (and concept). This format is used if you want to create named properties and/or methods.

If you don't need to create this context you may use just following:

User = function(){}

Here the constructor function is anonymous and doesn't create any context. For the same reason the new keyword is not needed.

Upvotes: 0

djechlin
djechlin

Reputation: 60768

It means User is a function that takes no inputs, has no side effects and returns nothing.

Most likely it is a class constructor and methods will be added to it later. User.foo = function() { /* ... */} would imply a static method, so this is more like a utilities class if you're used to thinking in Java architecture.

You should look up pseudo-classical inheritance in Javascript. Analogizing to Java, the code would be adding static methods to the User class, not object.

I'm still pretty convinced the code is following Java class patterns because the writer would prefer User to be a constructor that can be instantiated, has static methods, and has no instance methods (that I saw), over an object with properties that are functions. You are right that this is circuitous, but it's what the writer would do if they are a Java developer. It does have the advantage that instance methods may be added to User later with little client-code impact but I see no evidence this will happen to User (I didn't look long).

By the way, I deduced this because CapitalizedNames for functions implies it should be called with new in Javascript engineering in general, which implies it's a class. Figuring out why a class might be preferable just has to do with Java experience.

Upvotes: 7

Related Questions