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

Asked

Viewed 107 times

1

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

Example:

Joint declaration of a function:

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

fn(); // 'do

Statement (I don’t know if that’s what it’s called) at the same time 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 this were of appointment of functions?

  • 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 is only for that scope)?

1 answer

0


According to this reply in the SOEN, are named as follows:

Function declaration or function statement

In that case it is the joint declaration of function.

Example:

function fn()
{
}

named Function Expression Named function expression

In this case, it is an expression passed as callback of another function call, to which if a name is given, it 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 an expression named, passed by callback of fadeIn. It was also possible to assign the expression fade the attribute id.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.