The Group
function is being used as a constructor; your intuition is basically correct.
There is no good reason not to use an anonymous function expression like this.showItem = function(args){...};
, unless you wanted to reuse the local variable showItem
.
I'm not sure which syntax you mean. The function(args){...}
is an anonymous function expression, and the this.showItem
is referring to a member of the object this
. Taken all together, I suppose you could call it "setting a member function of an object".
Bonus tip (which maybe you already knew?): the reason you can use showItem
before its definition is due to function hoisting.
EDIT:
You seem to be asking about function expressions versus function declarations as well as named versus anonymous functions. The primary differences are:
Function declarations always stand on their own. They are never part of another operation, e.g. assignment. Your first example uses the function declaration function showItem(args) {...}
. Function expressions are used as an expression in some operation (e.g., assignment, passed as an argument, etc.). Your second case uses a function expression.
Function declarations are hoisted to the top of the current function scope, so showItem
in your first case is defined and contains the function when you use it in your assignment operation. Function expressions are not hoisted.
Function declarations are always named. Function expressions may be named or anonymous. When a function is defined with a name, that name is accessible as the name
property of the function object. A function's name is immutable and independent of any variables that hold a reference to the function. Also, code inside the function body can refer to the function by its name as a local variable (which is sometimes useful for recursion inside named function expressions).
To review:
- Function definition:
function showItems(args){...};
- Anonymous function expression:
this.showItems = function(args){...};
- Named function expression:
this.showItems = function showItemsName(args){...};
In the first case, there is a local variable called showItems
defined and the definition of showItems
is hoisted to the top. The difference between the latter two cases is that this.showItems.name
will be "showItemsName
" for the third case and undefined
for the second. Also, showItemsName
will be a local variable within the function body of the third function that holds a reference to the function object.