A function is a block of code wrapped in curly braces, preceded by a keyword function:
Copy Code code as follows:
function functionname ()
{
Here is the code to execute
}
function arguments
A function can have as many arguments as you want without declaring the variable type, using only the name of the variable:
Copy Code code as follows:
function MyFunction (name, job)
{
Here is the code to execute
}
function return value
Using the return statement in a function, the function stops executing and returns to where it was invoked.
The return value of the function does not have to declare the type, and it can be returned directly.
Copy Code code as follows:
function MyFunction ()
{
var x=5;
return x;
}
The above function returns the return value of 5.
Note: The entire JavaScript does not stop execution, just a function.
JavaScript will continue to execute code from the place where the function is invoked.
The function call is replaced by the return value:
Copy Code code as follows:
You can also use the return statement when you want to exit the function only.
The return value is optional:
Copy Code code as follows:
function MyFunction (a,b)
{
if (a>b)
{
Return
}
X=a+b;
}
When a is greater than B, it is not carried down, but returned directly.
Local variables
About local and global variables say it again.
A variable declared inside a JavaScript function (using VAR) is a local variable, so it can only be accessed within the function. (The scope of the variable is local).
You can use local variables with the same name in different functions, because only the function that declares the variable can recognize the variable.
The local variable is deleted as soon as the function completes.
Global variables
Variables declared outside a function are global variables and can be accessed by all scripts and functions on the Web page.
Note: Assign values to undeclared JavaScript variables:
If you assign a value to a variable that has not yet been declared, the variable is automatically declared as a global variable.
This statement:
Carname= "Volvo";
A global variable, carname, is declared even if it executes within a function.
function instance
Copy Code code as follows:
<body>
<script type= "Text/javascript" >
function member (name, job)//Analogy Java constructor, JS is not the concept of class
{
THIS.name = name;
This.job = job;
}
function Showproperty (obj, objstring) {
var str = "";
for (var i in obj) {
Traversing each property in an object
STR + + objstring + "." + i + "=" + Obj[i] + "<br/>";
I represents properties
Obj[i] Represents the value of this property
}
return str;
}
var obj = new Member ("Andy Lau", "entertainer")//Create object instance
Document.writeln (Showproperty (obj, "person"));
</script>
</body>
Output:
Copy Code code as follows:
Person.name= Andy Lau
person.job= artist
The above is the entire content of this article, I hope that the small partners can enjoy, have questions please give me a message.