Javascript: explain this syntax to me - javascript

JS newbie here, I've been looking through some code recently which uses syntax I'm not too familiar with. Here's an example, followed by my questions:
function Group(args) {
this.showItem = showItem;
function showItem(args) {
...
}
}
var group = new Group (args);
Questions:
As I understand it creating function Group and then instantiating via group = new Group is essentially prototypal equivalent of defining a class and then instantiating an object of that class. Is that correct?
Regarding the properties (methods?) of Group, what is the above syntax for showItem called? Why not just define it like:
this.showItem = function(args){...};
Would changing the code to the above change any different behavior?
If you did define it as above, what is that syntax called?

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.

The Group function is used as a constructor. However, the way this is done is a bit inefficient. What this code is doing is creating a new function and attaching it to the constructed object. He may be doing this because he wants to create a closure (i.e. use a variable only present in the namespace of the constructor), but absent that reason it's better to do this:
function Group(args){}
Group.prototype.showItem = function(args) {};
This way the same showItem function is shared among all objects constructed by Group via the prototype chain.
The benefit of using the original code vs an anonymous function is that the function has a name--this is a great help in debugging because reading a traceback full of anonymous function calls is no fun! To expand, there are three types of things that use the function keyword:
Function declarations When at the top level of a program or a function (i.e., of something that creates/has its own namespace), you may declare a function with a name. (The name stays with the function object throughout the program and will appear in tracebacks.) This is function showItem(args) {} in your example. (Note that this is only a function declaration at the top level of a file or function. There's a very similar thing I'll get to last.) By convention most people seem to omit semicolons after these.
Function expressions When part of an expression (such as assignment, return, etc), it is a function expression. The identifier part of the function expression is optional, so these are both function expressions:
var myfunc1 = function(){};
var myfunc2 = function MyFunctionName(){};
The second form is called a "named function expression". The great benefit of using this form is that MyFunctionName is no longer an anonymous function--this name will be attached to the function and will show up in tracebacks (for example). However there is a very serious bug in JScript (IE <= 8) that makes using these problematic. Read the article I linked above for details.
Finally, there is a common extension syntax called function statements. These look exactly like function declarations, except they are not top level! For example:
function() {
function foo(){} // function declaration
if (1) {
function bar(){} // function STATEMENT--not standard JS!
}
}
You should not rely on this extension, but should do this instead:
function() {
var bar;
if (1) {
bar = function bar(){};
}
}
this.showItem = function(){} would be called a "function expression in an assignment", and the original code is just using a "function declaration".

Related

Differences Between Named and Unnamed Anonymous Javascript Functions

Normally, in Javascript, when I want to pass an anonymous/inline function as an argument to another function, I do one of the following.
someFunctionCall(function() {
//...
});
someFunctionCall( () => {
//...
});
However, I've recently inherited a codebase that uses named function as inline arguments, like this
someFunctionCall(function foo() {
//...
});
I've never seen this syntax before. The function still seems to be anonymous -- there's no foo function defined in either the calling or called scope. Is this just a matter of style, or can using a named function (foo above) as an anonymous function change the behavior or state of that program?
This is specifically for a NodeJS (not a browser based program) program, and I'm specifically interested in behavior specific to using functions as parameters. That said information from behavior across platforms and runtimes is welcome.
There are at least three advantages of using named function expressions instead of anonymous function expressions.
Makes debugging easier as the function name shows up in call hierarchy.
The function name is accessible in the inner scope of the function, so it can be used for recursion
The function name itself acts like a self documentation of what the function is doing instead of reading the code.
Using those "named anonymous functions" won't change the behavior but will show the function name in stack traces which is very useful. Also the function gets callable within itself that way.
I'll give an example
Case 1:
var obj = {count: 0, counter: ()=> {this.count+=1;}}
If you do console.log(obj.count) you'll get 0
Case 2:
var obj = {count: 0, counter (){this.count+=1;}}
In 2nd case if you do console.log(obj.count) value will be one.
Hope you understood by now. Lamda expressions cannot access values with reference of this object. It can only access variables with global reference.
In case 1 if you want to make it work with lamba you have to use obj.count+=1 with name has reference.
And rest of the JavaScript function implementation remains same there is not much difference.

Why can I not .bind(this) when a function is directly declared

Given the following:
function x() {
this.abc = 1;
function f1() {
alert(this.abc);
}.bind(this)
var f2 = function b() {
alert(this.abc);
}.bind(this);
}
What I would like is for the "this" of the outer function to be available inside the f1 and f2 functions.
Why is it that VS2013 tells me there's a syntax error with the bind(this) on function f1() ?
There's a difference between a function declaration statement and a function instantiation expression. Both involve the keyword function, but a declaration statement cannot immediately be used as a reference to a function. A function instantiation expression is part of the expression grammar, so it can be used freely in that context as a reference to a function because that's what it evaluates to.
You can of course do this:
(function a() {
}).bind(this);
though without using the return value from .bind() it's not very useful.
If the first token in a statement is function, then you've got a function declaration statement. If the first token is not function, then you've either got another sort of keyword-introduced statement (for, return, var, try, whatever), or else you've got an expression statement. In that expression (or in any expression in another context), your function instantiations are part of the expression grammar and the value can be used as a reference to a function.
Here's another way to think about the problem. Let's pretend that there is only one way to instantiate a function in JavaScript, and that's the function expression. That is, let's pretend that any use of the function keyword means to instantiate a function and return a reference to that function as it's value.
Now, thinking generally about expressions and the things that participate in expressions, the point is to compute some sort of value. When you need the value 5 as part of an expression, you put 5 in its place and that's that. By itself, 5 is a valid expression, so this is not a syntax error:
5;
What does that do, however? It does nothing. Similarly, in our make-believe JavaScript without function declaration statements,
function foo(a, b) {
return a + b;
};
would also do nothing at all. What would happen is simply that the function would be instantiated but thrown away because the value — the reference to the instantiated function — is not saved as the value of a variable or passed to some function or anything else. In this make-believe JavaScript, you'd use
var foo = function(a, b) {
return a + b;
};
all the time.
The language design does have function declaration statements, however. As a simplifying approach, the language just recognizes a statement whose first token is the keyword function as a completely different sort of statement than an expression statement that happens to contain a function instantiation. There are other ways in which the problem could have been addressed (such as the use of a different keyword), but I suspect that there'd still be confusion.
Note that there are JavaScript programmers who strongly prefer using var declarations for functions. It's a matter of style really.

Is this an anonymous function?

In the first snippet below, based on my understanding I am creating a function and assigning it to a variable. But does that mean the function will take that name of the variable ?
var aFunc = function(){};
I know this is named function.
function bFunc(){};
So, first of all we have to clarify the main difference between the two functions you wrote.
This one:
var aFunc = function(){};
is a function expression. Where this one:
function bFunc(){};
is a function declaration.
In a function expression you're using the function operator to defines a function inside an expression.
When you declare a function you're using the function statement.
At the beginning it can be confusing because they're really similar, however function declaration and function expression behaves differently. First of all, you can't declare a function that is anonymous: if you're using a function statement, the name is mandatory.
So only functions defined with the function operator can be anonymous:
var aFunc = function(){};
That's an anonymous function. In some browsers you can actually print the function's name and see by yourself:
console.log(aFunc.name);
(Notice that this is not standard yet, but there is a proposal)
But it doesn't means that functions declared with the function operator have to be anonymous. For instance:
var aFunc = function myFunction() {};
It's a named function. However, that's still different from having a function declaration like that:
function myFunction() {};
var aFunc = myFunction;
Why? Because in case of function expression, you don't declare a myFunction function in the scope:
var aFunc = function myFunction() {};
console.log(typeof myFunction) // undefined, unless some bugs
So what's the point to give a name to a function expression? The answer is: to have access from that function from the function's body itself, without pollute the scope. Imaging for instance you want to add an event listener to a DOM node, but execute the listener only once:
document.body.addEventListener("click", function onclick() {
// do something
document.body.removeEventListener("click", onclick, false);
}, false);
So you don't pollute the scope with a lot of functions that you use only for purpose like that ones, and you can still have access to the function from the function's body. That's especially useful in ES5 where arguments.callee is deprecated, and for recursion.
Another difference between function expression is that you can invoke them immediately, but you can't do that for function declaration. So, for instance:
function() {
console.log('foo');
}();
Will throw an exception, because the engine can't understand if it's a function declaration or a function expression. But if you force the engine to look at it as an expression:
!function() {
console.log('foo');
}();
// or
(function(){
console.log('foo');
}());
// etc, there are a lot of ways
Here we are: JS understand is an expression, therefore threats the function as an operator and not as a statement. And you obtain the IIFE (Immediately-Invoked Function Expression), that are useful in a lot of scenarios, specially where you want to isolate code.
So, back to you question, why the name of this function:
var aFunc = function(){};
is not aFunc?
Because, it's an expression. So the value knows nothing about the assignment on the left. It's like having:
var aFunc = -3;
Where the - is the Unary Negation operation and the 3 is the value: they knows nothing about aFunc, right? It's exactly the same with function expression, where function is the operator, and (){} is the value.
No.
In the first example you are creating an anonymous function and then assigning it to "aFunc"
In the second example you declare a function and call it bFunc.
The most notable difference between the two is that you can't call "aFunc" until after the line where you assign it.
No, the function will not "take the name of the variable". The variable will hold a reference to an anonymous function. The function itself is still anonymous.
Note that this makes little difference in the end though, this function reference can be treated exactly the same as any regular named function once it's assigned. In fact, it makes so little difference, a named function can be treated like a variable holding a function reference too:
function foo() { }
foo();
foo = 'bar';
alert(foo); // bar
The term "anonymous function" is jargon, so likely what it means will change over time. There is no specification that states what it is, so it can be whatever you want it to be. And whatever you decide will likely be disputed by someone else. Jargon is like that (look up the word "trunking", a common jargon term in telephony).
Strictly, there are function declarations where the name is mandatory, e.g.
function foo() {
...
}
and function expressions where the name is optional. If the name is missing, e.g.:
var x = function () {
...
};
then that, to me, is an anonymous function. If it has a name, e.g.
var x = function foo() {
...
};
then it's a named function expression (and not an anonymous function). From my perspective, any function expression without an optional name is an anonymous function. There are many uses for function expressions, e.g.
// assignment to a variable
var x = function() {...}
// pass as a parameter
foo(function(){...})
// immediately executed and pass the result
foo( (function(){...}()) )
and so on. So in the OP, the right hand side of the assignment is a function expression with no name so to me, that's an anonymous function. The fact that it's then assigned to an identifier doesn't suddenly make it a named function expression.
Others may differ of course.
Incidentally, the results of:
function foo(){}
and
var foo = function(){};
are practically indistinguishable, the main difference is when the functions are created.
No it is not. The right hand side of your first statement is a Function Expression. It is anonymous as long as you don't assign it to a variable.
After you have assigned it, you can use it as a declared function.
See more details about function declarations in this question

Two functions with the same name in JavaScript - how can this work?

As far as I know, function foo() { aaa(); } is just var foo = function(){ aaa() } in JavaScript. So adding function foo() { bbb(); } should either overwrite the foo variable, or ignore the second definition - that's not the point. The point is that there should be one variable foo.
So, in this example the me variable should not be correctly resolved from inside the methods and it is not in Explorer 8 :-). I came to this example by trying to wrap them into another closure where (var) me would be, but I was surprised that it's not necessary:
var foo = {
bar1 : function me() {
var index = 1;
alert(me);
},
bar2 : function me() {
var index = 2;
alert(me);
}
};
foo.bar1(); // Shows the first one
foo.bar2(); // Shows the second one
Demo: http://jsfiddle.net/W5dqy/5/
AFAIK function foo() { aaa(); } is just var foo = function(){ aaa() } in JavaScript.
Not quite; they're similar, but also quite different. JavaScript has two different but related things: Function declarations (your first example there), and function expressions (your second, which you then assign to a variable). They happen at different times in the parsing cycle and have different effects.
This is a function declaration:
function foo() {
// ...
}
Function declarations are processed upon entry into the enclosing scope, before any step-by-step code is executed.
This is a function expression (specifically, an anonymous one):
var foo = function() {
// ...
};
Function expressions are processed as part of the step-by-step code, at the point where they appear (just like any other expression).
Your quoted code is using a named function expression, which look like this:
var x = function foo() {
// ...
};
(In your case it's within an object literal, so it's on the right-hand side of an : instead of an =, but it's still a named function expression.)
That's perfectly valid, ignoring implementation bugs (more in a moment). It creates a function with the name foo, doesn't put foo in the enclosing scope, and then assigns that function to the x variable (all of this happening when the expression is encountered in the step-by-step code). When I say it doesn't put foo in the enclosing scope, I mean exactly that:
var x = function foo() {
alert(typeof foo); // alerts "function" (in compliant implementations)
};
alert(typeof foo); // alerts "undefined" (in compliant implementations)
Note how that's different from the way function declarations work (where the function's name is added to the enclosing scope).
Named function expressions work on compliant implementations. Historically, there were bugs in implementations (early Safari, IE8 and earlier). Modern implementations get them right, including IE9 and up. (More here: Double take and here: Named function expressions demystified.)
So, in this example the me variable shoudl not be corectly resolved from inside the methods
Actually, it should be. A function's true name (the symbol between function and the opening parenthesis) is always in-scope within the function (whether the function is from a declaration or a named function expression).
NOTE: The below was written in 2011. With the advances in JavaScript since, I no longer feel the need to do things like the below unless I know I'm going to be dealing with IE8 (which is very rare these days).
Because of implementation bugs, I used to avoid named function expressions. You can do that in your example by just removing the me names, but I prefer named functions, and so for what it's worth, here's how I used to write your object:
var foo = (function(){
var publicSymbols = {};
publicSymbols.bar1 = bar1_me;
function bar1_me() {
var index = 1;
alert(bar1_me);
}
publicSymbols.bar2 = bar2_me;
function bar2_me() {
var index = 2;
alert(bar2_me);
}
return publicSymbols;
})();
(Except I'd probably use a shorter name than publicSymbols.)
Here's how that gets processed:
An anonymous enclosing function is created when the var foo = ... line is encountered in the step-by-step code, and then it is called (because I have the () at the very end).
Upon entry into the execution context created by that anonymous function, the bar1_me and bar2_me function declarations are processed and those symbols are added to the scope inside that anonymous function (technically, to the variable object for the execution context).
The publicSymbols symbol is added to the scope inside the anonymous function. (More: Poor misunderstood var)
Step-by-step code begins by assigning {} to publicSymbols.
Step-by-step code continues with publicSymbols.bar1 = bar1_me; and publicSymbols.bar2 = bar2_me;, and finally return publicSymbols;
The anonymous function's result is assigned to foo.
These days, though, unless I'm writing code I know needs to support IE8 (sadly, as I write this in November 2015 it still has significant global market share, but happily that share is plummetting), I don't worry about it. All modern JavaScript engines understand them just fine.
You can also write that like this:
var foo = (function(){
return {
bar1: bar1_me,
bar2: bar2_me
};
function bar1_me() {
var index = 1;
alert(bar1_me);
}
function bar2_me() {
var index = 2;
alert(bar2_me);
}
})();
...since those are function declarations, and thus are hoisted. I don't usually do it like that, as I find it easier to do maintenance on large structures if I do the declaration and the assignment to the property next to each other (or, if not writing for IE8, on the same line).
Both me lookups, are only visible/available inside the function expression.
Infact those two are named function expressions, and the ECMAscript specification tells us, that the name of an expression is not exposed to the such called Variable object.
Well I tried to put that only in a few words, but while trying to find the right words, this ends up in pretty deep chain of ECMAscript behavior. So, function expression are not stored in a Variable / Activation Object. (Would lead to the question, who those guys are...).
Short: Every time a function is called, a new Context is created. There is some "blackmagic" kind of guy that is called, Activation object which stores some stuff. For instance, the
arguments of the function
the [[Scope]]
any variables created by var
For instance:
function foo(test, bar) {
var hello = "world";
function visible() {
}
(function ghost() {
}());
}
The Activation Object for foo would look like:
arguments: test, bar
variables: hello (string), visible (function)
[[Scope]]: (possible parent function-context), Global Object
ghost is not stored in the AO! it would just be accesssible under that name within the function itself. While visible() is a function declaration (or function statement) it is stored in the AO. This is because, a function declaration is evaluated when parsing and function expression is evaluated at runtime.
What happens here is that function() has many different meanings and uses.
When I say
bar1 : function me() {
}
then that's 100% equivalent to
bar1 : function() {
}
i.e. the name doesn't matter when you use function to assign the variable bar1. Inside, me is assigned but as soon as the function definition is left (when you assign bar2), me is created again as a local variable for the function definition that is stored in bar2.

What is the difference between JavaScript class definitions styles?

I am not clear on the actual difference between these two styles of "class" definitions in JavaScript.
Method a:
function myclass() {}
Method b:
myclass = function() {}
Is there any difference?
Those are functions, the first one is a function declaration, the second is a variable assignment with a function expression.
The main difference is that the function declarations are hoisted up in the current scope at parse time, they behave like if you declared them at the top of its enclosing scope.
The grammar of both is very similar, the only grammatical difference is that the name function expressions is optional, the parser knows which one you are using based on the "context" where you use it, e.g. your first example is a function declaration because the function itself is defined on a Program (technically a place outside of any function, in the global scope), or in FunctionBody (inside a function).
A function expression is created when it is evaluated itself in expression context, e.g.:
function foo () {} // function declaration
(function foo() {}); // function expression
In the above example the second one is interpreted as a function expression because is surrounded by parentheses, and parentheses can only hold expressions...
I highly recommend you the following in-depth article about the topic:
Named function expressions demystified
The latter is a closure which you are assigning to a variable. As soon as the variable is deleted (or is assigned a different value) you won't be able to call the function anymore. Besides that both are pretty much the same as functions are first class citizens in Javascript.
Firstly, you're defining functions, not classes.
Secondly, the second definition will put the myclass into the global namespace, whereas the first will not (it would be defined in function scope instead). However, so far as I'm aware, the following are roughly equivalent:
function myclass() {}
and
var myclass = function() {}
There are some small differences, which are explored over on developer.mozilla.org. Having said that, I've never noticed any of the differences.
In the second case, you are declaring the function as a variable. It is particularly useful for something like this in OOP:
var myObject = new Object();
myObject.add = function(a,b) {
return a + b;
};
myObject.add(1, 2);

Categories

Resources