JavaScript code block
C# code block
protected void Page_Load(object sender, EventArgs e)
{
TestFactory();
}
public delegate int factorialDelegate(int num); //Define recursive function delegate
private void TestFactorial()
{
factorialDelegate fdelegate = factorial; //Please note the comparison with javascript function
factorialDelegate trueFactorial = fdelegate;
fdelegate = returnZero;
int num1 = trueFactorial(5); //120
int num2 = fdelegate(5); //0
}
private int returnZero( int num)
{
return 0;
}
private int factorial(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return num * factorial(num - 1);
}
}
From the above, it can be seen :
1. Functions in JavaScript do not need to set whether the function has a return value. In this case, of course there is no need to set the return value type of the function.
2. The function in JavaScript is actually an object. This is very different from the strongly typed languages (C, C, C#) we are exposed to.
3. There is an array-like object arguments in JavaScript, which contains all parameters passed into the function. And this object also has an attribute called callee, which is a pointer to the function that owns the arguments object. If you look at the C# code block, the execution of the trueFactory delegate and the function factorial are tightly coupled. There is no way to eliminate this tight coupling. In the above javascript code block, when the variable trueFacttorial obtains the value of factorial. Then, we simply assign a function that returns 0 to the factorial variable. If arguments.callee is not used as usual, calling trueFacttorial() will return 0. After decoupling the code in the function body from the function name, trueFactory() can still calculate the factorial normally. As for factorial(), it is just a function that returns 0 now.
Reference book "
Javascript Advanced Programming"
Part of the text comes from the above books
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn