DECLARING A FUNCTION | ||||||
| ||||||
| ||||||
FUNCTION AS AN OBJECT | ||||||
|
Run example.
We can even print the content of the object and it will output the actual code of the function: Example 2: Click alert(Ball); to see content of Ball.
We can add properties to Objects, including function objects. Since the act of declaring a function creates an object. We can, potentially add properties to that function. For example, here we declare function Ball, and added callsign property.
Example 3
Run example.
>
Since function is an object, we can assign a pointer to a function. For example, below, the variable ptr points to myFunction object.
Example 4
Run example.
We can execute the function as if the function name has been replaced by the pointer name. So above, the line ptr("hello"); has the same meaning as this: myFunction("hello");
Pointer to a function is useful in object oriented programming. For instance: when we want several objects to point to the same function like below:
Example 4A
Run example.
Example 5:
Run example.
We can reassign function after you created it, but we need to refer to the function object itself, not a pointer to it. For example, below I changed the content of myfunction().
Example 6:
Run example.
Where has the old function gone? Into oblivion.
If we want to save it, we can assign a pointer to it before changing it.
Run example.
Be careful, the example below won't work because instead of modifying the function, the code below creates another function which is called myFunctionPtr.
Example 6B:
Run example.
We can nest a function within a function. For example, below I have a function called getHalfOf, and within it I have another function called calculate.
Example 7
}Run example.
You can only call a nested function locally. That is, you cannot call: getHalfOf.calculate(10) because calculate only exists when the outer function (getHalfOf()) is run. This is consistent with our discussion above (function is compiled, but not executed until you call it).
You might be wondering about naming collision. For example, which calculate function will be called below?
Example 8
}Run example.
In cases like this, the compiler will first look on the local address space, so it will use the nested calculate function. If we erase the nested/local calculate function, then that code will use the global calculate function.