<head>
<meta charset="UTF-8">
<title>js函数</title>
</head>
<body>
<!--
函数: 相当于java的方法
声明函数的语法(3种):
1. 显式声明:
语法:
function 函数名(形参列表){
//函数体代码
}
使用: 函数名(实参);
注: 显式声明的函数可以在函数声明前使用
2. 隐式声明:
语法:
let 函数名 = function(形参){
}
注1: 只能在声明后使用
注2: 可以在使用过程中更换函数内容
3. 匿名声明:
语法:
function(){
}
注1: 声明时直接使用. 一次性函数
(function(形参){
})(实参);
注2: 作为另一个函数的实参使用
-->
</body>
<script>
test4("we");//js函数形参与实参的数量可以不对应
//1:显式声明:
function test1() {
document.write("我是显式函数1无参<br>")
}
test1();
document.write("<hr>");
function test2(a) {
document.write("我是显式函数2带参"+a+"<br>");
}
test2("我是参数");
function test4(a,b,c) {
document.write("我是显式函数a"+a+"<br>");
document.write("我是显式函数b"+b+"<br>");
document.write("我是显式函数c"+c+"<br>");
a = a||null;
}
//返回值
function test5(a,b) {
return a+b;
}
var c = test5(1,2);
document.write("我是显式返回值"+c+"<br>");
</script>
<script src="js/js.js"></script>
<script>
/*当引用外部文件中的函数时,引用的函数必须放到引用标签之后*/
test3();
</script>
--------------------------------------------------------------------------------------------------------------
<head>
<meta charset="UTF-8">
<title>隐式函数</title>
</head>
<body>
<!--<div onclick="num2()" ></div>-->
<input type="button" onclick="num2()" value="测试函数内容变更">
</body>
<script>
//2:隐式函数,实际上时一个变量,只能在声明后使用
//num1();//在声明前调用不会有任何结果
var num1 = function () {
document.write("我是隐式一号<br>");
}
num1();
//注:可以在使用过程中更换函数内容
document.write("<hr>");
//函数内容更换
var num2 = test1;
function test1() {
//document.write("我是隐式test1<br>");
alert("我是隐式test1");
num2 = test2;
}
function test2() {
//document.write("我是隐式test2<br>");
alert("我是隐式test2");
num2=test1;
}
/* num2();
num2();
num2();*/
</script>
-------------------------------------------------------------------------------------
<head>
<meta charset="UTF-8">
<title>3匿名函数</title>
</head>
<body>
<!--
3. 匿名声明:
语法:
function(){
}
注1: 声明时直接使用. 一次性函数
(function(形参){
})(实参);
注2: 作为另一个函数的实参使用
-->
</body>
<script>
//1直接使用
(function() {
document.write("我是匿名函数测试1<br>");
document.write(3*2+"我是匿名函数测试1<br>");
})()
//作为另外一个函数的参数
test1(function () {
document.write("我是匿名函数作为参数1<br>");
})
test1(function () {
document.write("我是匿名函数作为参数2<br>");
})
function test1(fn) {
fn();
}
</script>