Some languages (Javascript, Python) have the notion that a function is an object:
//Javascript
var fn = console.log;
//Javascript
var fn = console.log;
This means that functions can be treated like any other object (first-class functions), e.g. passed in as an argument to another function:
var invoker = function(toInvoke) {
toInvoke();
};
invoker(fn); //will call console.log
var invoker = function(toInvoke) {
toInvoke();
};
invoker(fn); //will call console.log
Other languages (C++, C#, VB.NET) do not define functions as real objects:
//C#
Type t = Console.WriteLine.GetType();
//This code will not compile, because:
//"'Console.WriteLine()' is a method, which is not valid in the given context"
//C#
Type t = Console.WriteLine.GetType();
//This code will not compile, because:
//"'Console.WriteLine()' is a method, which is not valid in the given context"
Rather these languages may have objects which can point to a function (such as C++ function pointers) and can be passed around just like any other object. In the CLI, these wrapper objects are called delegates or delegate instances:
//C#
void Invoker(Action toInvoke) {
toInvoke();
}
Action action = Console.WriteLine;
Invoker(action);
//also valid, and the toInvoke argument will now contain a delegate which points to Console.WriteLine
//Invoker(Console.WriteLine);
//C#
void Invoker(Action toInvoke) {
toInvoke();
}
Action action = Console.WriteLine;
Invoker(action);
//also valid, and the toInvoke argument will now contain a delegate which points to Console.WriteLine
//Invoker(Console.WriteLine);
What differences in capability arise from these two mechanisms -- "function object" vs "pointer-to-function as object"?