Delegate (similar to C #) in JavaScript

3

One feature I use extensively in C # is delegate which is a reference type used to reference anonymous or named methods. Especially the classes already implemented in the framework such as Action and Func , as shown 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 do not know how to do this, it may even be something very simple. In Java 6 that does not support this type of behavior, I remember that to get around this and do something similar I used an interface that could be implemented anonymously, as shown 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");
    }
}

Is this approach possible in JavaScript?

    
asked by anonymous 20.07.2016 / 19:12

1 answer

3

JavaScript has a similar feature, not to say identical to delegate . It is the anonymous function, which is basically the same concept as the delegate. It can take the form of closure . is usually used as callback as well as delegates.

Just as delegates the anonymous function is a body of code that is allocated somewhere and a pointer is assigned to a variable, you can transfer that reference to other variables, including parameters. Then just declare the function inside the variable .

Its use is very simple. The usage details can be obtained from the links above.

    
20.07.2016 / 20:24