A function will be executed by an event or by a call to the
function.
How to Define a Function
To keep the browser from executing a script when the page loads, you can put your script into a function.A function contains code that will be executed by an event or by a call to the function.
You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section.
Syntax
function functionname(var1,var2,...,varX)
{
some code
}
The parameters var1, var2, etc. are variables or values passed into the
function. The { and the } defines the start and end of the function.{
some code
}
Note: A function with no parameters must include the parentheses () after the function name.
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.
Example
<html>
<head>
<script
type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button"
value="Click me!" onclick="displaymessage()" />
</form>
<p>By pressing the button
above, a function will be called. The function will alert a message.</p>
</body>
</html>
You will learn more about JavaScript events in the JS Events chapter.
The return Statement
The return statement is used to specify the value that is returned from the function.So, functions that are going to return a value must use the return statement.
The example below returns the product of two numbers (a and b):
Example
<html>
<head>
<script
type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script
type="text/javascript">
document.write(product(7,3));
</script>
<p>The script in the body
section calls a function with two parameters (4 and 3).</p>
<p>The function will return
the product of these two parameters.</p>
</body>
</html>
The Lifetime of JavaScript Variables
If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
No comments:
Post a Comment