JavaScript Tutorial/Function/Function Definition

Материал из Web эксперт
Версия от 11:24, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Calculation in function

   <source lang="javascript">

<html> <head> <title>A Simple Page</title> <script language="JavaScript">

</script> </head> <body> <input type="button" value="Convert Celsius to Fahrenheit" onClick="inputCels();">

<input type="button" value="Convert Fahrenheit to Celsius" onClick="inputFah();"> </body> </html></source>


Define a function

   <source lang="javascript">

<html> <head> <title>Function Demo</title> <script language="javascript" type="text/javascript">

</script> </head> <body>

Function Demo

</body> </html></source>


Define the simplest function

   <source lang="javascript">

<html> <head> <title>A Simple Page</title> <script language="JavaScript">

</script> </head> <body> </body> </html></source>


Functions

All function declaration must begin with the keyword function followed by the name of the function.

Parentheses are placed after the function name to hold arguments.

If more than one argument are used, use commas to separate the arguments.

If no arguments, leave the space between the parentheses empty.

Curly brackets are used to contain the code related to the function.

Curly brackets are not optional.

JavaScript uses call by value.



   <source lang="javascript">

<html> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </html></source>


Recursive function

   <source lang="javascript">

<HTML> <HEAD>

  <SCRIPT>
  function fib (inNum) {
     if (inNum == 0) 
       var fibNum = 0;
     else{
       if (inNum == 1)
          fibNum = 1;
       else{
          fibNum = fib(inNum - 2) + fib(inNum - 1);
       }
    }
    return fibNum;
  }
  function writeFibs(topFib) {
     for (var i=0;  i <= topFib ; i++) {
       document.write ("Fib(" + i + ") = " + fib(i) + " 
"); } } </SCRIPT>

</HEAD> <BODY>

  <FORM Name="theForm">
  <INPUT Type=Text Name="numFibs">
  <INPUT Type=Button Value="Show Fibs" onClick="writeFibs(numFibs.value);">

</FORM> </BODY> </HTML></source>