Named Functional Expressions

Lecture




  1. Named Function Expression
  2. Usage example
  3. Total

Usually, what is called a “function name” is, in fact, the name of the variable to which the function is assigned. To the function itself, this “name” is in no way attached. If the function is moved to another variable, it will change the “name”:

1 function f() { alert(1); }; f() { alert(1); };
2 g = f;
3 f = 0;
4
5 g(); // сменили имя f на g!

However, there is a way in JavaScript to specify a name that is actually associated with a function. It is called Named Function Expression (NFE) or, in Russian, a named functional expression .

Named Function Expression

The simplest example of NFE looks like this:

var f = function sayHi (...) { /* тело функции */ };

Simply put, NFE is a Function Expression with an additional name (in the example above sayHi ).

What is this name that goes in addition to the variable f , and why is it?

The name of the functional expression ( sayHi ) has a special meaning. It is available only from within the function itself.

This visibility limit is included in the JavaScript standard and is supported by all browsers except IE8-.

For example:

1 var f = function sayHi(name) {
2    alert(sayHi); // изнутри функции - видно (выведет код функции)
3 };
4
5 alert(sayHi); // снаружи - не видно (ошибка: undefined variable 'sayHi')

Another fundamental difference between a name and a regular variable is that it cannot be rewritten:

1 var test = function sayHi(name) {
2    sayHi = "тест" ;
3    alert(sayHi); // function... (перезапись не удалась)
4 };
5
6 test();

In use strict mode, the code above would give an error.

Obsolete special value of arguments.callee

If you've worked with JavaScript, you may know that the special value of arguments.callee also served for this purpose.

If this name doesn’t tell you anything - everything is in order, read on, we will definitely discuss it in a separate chapter.

If you are aware, it is worth bearing in mind that it is officially excluded from the modern standard. And NFE is our present.

Usage example

NFE is used primarily in situations where the function needs to be transferred to another place in the code or moved from one variable to another.

The internal name allows the function to reliably access itself, wherever it is.

Let us recall, for example, the factorial function from the Calculate factorial task:

1 function f(n) {
2    return n ? n*f(n-1) : 1; n ? n*f(n-1) : 1;
3 };
4
5 alert( f(5) ); // 120

Let's try to transfer it to another variable:

1 function f(n) {
2    return n ? n*f(n-1) : 1; n ? n*f(n-1) : 1;
3 };
4
5 var g = f;
6 f = null ;
7
8 alert( g(5) ); // ошибка при выполнении!

An error occurred because a function from its code refers to its old name f . And this function no longer exists, f = null .

In order for the function to always work reliably, we will declare it as the Named Function Expression:

1 var f = function factorial (n) {
2    return n ? n* factorial (n-1) : 1; n ? n* factorial (n-1) : 1;
3 };
4  
5 var g = f; // скопировали ссылку на функцию-факториал в g
6 f = null ;
7
8 alert( g(5) ); // 120, работает!

In the IE8 browser, two functions are created.

As we said above, in the IE browser up to version 9, the name NFE can be seen everywhere, which is an error from the point of view of the standard ... But in fact the situation is even funnier.

Old IE creates two functions in such cases: one is written to the variable f , and the second is written to the factorial variable.

For example:

1 var f = function factorial(n) { /*...*/ };
2
3 // в IE8- false
4 // в остальных браузерах ошибка, т.к. имя factorial не видно
5 alert(f === factorial);

All other browsers fully support named functional expressions.

Total

If the function is specified as Function Expression, it can be given a name. It will be available only inside the function (except IE8-) and is intended for reliable recursive function call, even if it is written to another variable.

Later in the tutorial, we will see more examples of using Named Function Expression for ease of development.

Importance: 5

What will be the result of code execution?

function g() { return 1; } 1; }
alert(g);

And this? Does it matter, if so - why?

( function g() { return 1; });
alert(g);

Decision

The first code will print function ... , the second one - an error in all browsers except IE8-.

1 // обычное объявление функции (Function Declaration)
2 function g() { return 1; }; 1; };
3
4 alert(g); // функция

In the second code, there is a bracket, so the function inside is not a Function Declaration , but part of the expression, that is, the Named Function Expression . His name is visible only inside, outside the variable g not defined.

1 // Named Function Expression!
2 ( function g() { return 1; });
3
4 alert(g); // Ошибка!

All browsers except IE8 support this visibility limit and will display an error, 'undefined variable'.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone