Delegate (similar to C#) in Javascript

Asked

Viewed 98 times

3

A feature I use a lot in C# is delegate which is a reference type used to reference anonymous or named methods. Especially classes already implemented in framework like the Action and the Func, as an example below.

public class Program
{
    public static void Main
    {
        ExibirMensagem((s) => 
        {
            Console.WriteLine(s);
        });
    }

    public static void ExibirMensagem(Action<T> actMensagem)
    {
        actMensagem("Exibiu a mensagem");
    }
}

I would need something similar to this, but in Javascript. I’m new to Javascript and I don’t know how to do this, it might be something very simple. In Java 6 that does not support this type of behavior, I remember that to get around it and do something similar I used an interface that could be implemented anonymously, as an example below:

public interface IAcao {
    void Executar(String str);
}

public class Program {
    public static void Main(string[] args) {
        ExecutarAcao(new IAcao() {
            @Override
            public void Executar(String str) {
                Log.v("Exec", str);
            }
        });
    }

    public static void ExecutarAcao(IAcao delAcao) {
        delAcao.Executar("Executou Ação");
    }
}

This approach is possible in Javascript?

1 answer

3


Javascript has a feature similar to delegate. It is the anonymous function, which at the bottom is the same concept of the delegate. It can take the form of closure. It’s usually used as callback, as well as the delegates. The delegate is a little more powerful, but in few things used and that make more sense in static typing language.

Just as delegates to the anonymous function is a body of code that is allocated somewhere and a pointer is assigned to a variable, it can transfer this reference to other variables, including parameters. So it’s just declare the function within the variable.

Its use is very simple. Details of use can be obtained from links placed above.

Browser other questions tagged

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