Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
Sanandrea Avatar asked Feb 08 '16 15:02

Sanandrea


1 Answers

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.

like image 100
djechlin Avatar answered Oct 13 '22 00:10

djechlin