What is the callback in javascript when it is named (directly in the declaration)?

1

How do you call the callback in javascript when it is named (directly in the statement)?

Example:

Common declaration of a function:

function fn()
{
    console.log(fn); // Imprime fn()
    return 'do';
}

fn(); // 'do

Declaration (I do not know if that's what it's called) at the same time that we go through callback:

call(function fn()
{
    console.log(fn); // Imprime: fn()
});

fn(); // Erro: função não foi definida

Another example:

$('element').on('action', function fn()
{
    if ($(this).next().size()) {
        fn.call(this);
    }
});

console.log(fn)// Erro: Função não definida
  • What is the difference of this naming function?

  • One is a statement and the other is an expression?

  • This can be called an anonymous function (since it has a name, even if it's just for that scope)?

asked by anonymous 18.08.2015 / 21:37

1 answer

0

According to this response in SOEN, they are named as follows:

function declaration

In this case it is the common declaration of the function.

Example:

function fn()
{
}

named function expression Named function expression

In this case, it is an expression passed as the callback of another function call, which is given a name, and can be referenced within the scope that is called.

Example:

$('.item').eq(0).fadeIn(500, function fade()
{
     fade.id = typeof(fade.id) == 'undefined' ? 1 : ++fade.id;

     if ($('.item').eq(fade.id).size()) {
        $('.item').eq(fade.id).fadeIn(500, fade);
     }
});

In this case, it is a named expression, passed by callback of fadeIn . It was also possible to assign the expression fade to the id attribute.

If we tried to access its attribute outside of that scope, there would be an error because it is a named function expression, not a function declared with that name.

    
19.08.2015 / 13:38