1, is a function of event-driven or reusable blocks of code when it is executed and.
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">点我</button>
2, JavaScript function syntax
Function block is wrapped in braces, the previously used Keywords function:
function functionname()
{
// 执行代码
}
JavaScript 对大小写敏感。关键词 function 必须是小写的,并且必须以与函数名称相同的大小写来调用函数
3, call the function with parameters
When you call the function, you can pass it a value, these values are called parameters.
These parameters may be used in the function.
You can send any number of parameters, (,), separated by commas:
myFunction (argument1, argument2)
When you declare a function, declare the parameters as variables:
function myFunction (var1, var2)
{
Code
}
<p>点击这个按钮,来调用带参数的函数。</p>
<button onclick="myFunction('Harry Potter','Wizard')">点击这里</button>
<script>
function myFunction(name,job){
alert("Welcome " + name + ", the " + job);
}
</script>
<p>请点击其中的一个按钮,来调用带参数的函数。</p>
<button onclick="myFunction('Harry Potter','Wizard')">点击这里</button>
<button onclick="myFunction('Bob','Builder')">点击这里</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
4, with the return value of the function
Sometimes we want the function to return the value of its local calling.
It can be achieved by using a return statement.
When using the return statement, the function stops execution and returns the specified value.
grammar
function myFunction()
{
var x=5;
return x;
}
The above function will return the value 5.
5, the function returns with a value
<p id="demo"></p>
<script>
function myFunction(a,b){
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
6, JavaScript scope
Scope is a collection of accessible variables.
7, JavaScript local scope
Variables declared within a function, variables local scope.
Local variables: can only be accessed within the function.
<p>局部变量在声明的函数外不可以访问。</p>
<p id="demo"></p>
<script>
myFunction();
document.getElementById("demo").innerHTML = "carName 的类型是:" + typeof carName;
function myFunction()
{
var carName = "Volvo";
}
</script>
8, JavaScript globals
Variables defined outside the function, i.e. a global variable.
Global variables have a global scope: pages all scripts and functions can be used.
<p>全局变量在任何脚本和函数内均可访问。</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
myFunction();
function myFunction()
{
document.getElementById("demo").innerHTML =
"我可以显示 " + carName;
}
</script>