JavaScript中的函数—通过function关键字定义函数
一 function函数名称([参数,…]) {
代码段;
return 返回值;
}
注意:
(1)函数名称不要包含特殊字符;
(2)函数名称最好含义明确;
(3)函数名称最好遵循驼峰标记法或者下划线法;
(4)函数名称严格区分大小写;
(5)函数名称如果重复会产生覆盖;
(6)函数可以有参数也可以没有参数,可以有一个参数也可以有多个参数;
(7)函数通过return加返回值,如果没有return默认返回undefined
(8)函数不调用不执行。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//test();
function test(){
alert('this is a test');
}
//test();
//函数名称严格区分大小写
function TEST(){
alert('hello king');
} function test(){
alert('this is a test');
}
//TEST();
//名称重复会产生覆盖
//test();
function test(){
alert('hello maizi');
}
// test();
function test1(){
alert('this is test1 function');
}
// alert(test1());
function test2(){
return 1.2;
alert('this is a test');
return 1;
}
//alert(test2());
function calc(num1,num2){
return num1+num2;
}
alert(calc(1,2));
//alert(window.calc(1,2)) ;
function calc1(num1,num2){
num1=num1||1;
num2=num2||2;
return num1+num2;
}
alert(calc(3,6));
</script>
</body>
</html>
二 调用函数
1.作为一个函数调用
(1)通过函数名称()调用,如果有参数传递相应参数即可;
(2)在HTML中默认的全局对象是HTML页面本身,所以函数是属于HTML页面。在浏览器中的页面对象是浏览窗口(window对象),所以函数会自动变为window对象的函数,也可以通过window。函数名称()进行调用;
2.全局对象
(1)当函数没有被自身的对象调用时,this的值就会变成全局对象。在web浏览器中全局对象是浏览器窗口window对象。
(2)函数作为全局对象调用,会使this的值称为全局对象。使用window对象作为一个变量容易造成程序崩溃;
3.函数作为方法调用【可以将函数定义为对象的方法进行调用】
4.使用构造函数调用函数【如果在函数调用前使用了new关键字,则调用了构造函数】
5.作为回调函数调用函数
(1)call();
(2)apply();
三 参数
1.函数可以有参数也可以没有参数,如果定义了参数,在调用函数的时候没有传值,默认设置为undefined;
2.在调用函数时如果传递参数超过了定义时的参数,JS会忽略掉多余参数;
3.JS中不能直接写默认值,可以通过arguments对象来实现默认效果;
4.可以通过arguments对象来实现可变参数的函数;
5.通过值传递参数在函数体内对变量做修改不会影响变量本身;
6.通过对象传递参数在函数体内变量做更改会影响变量本身;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//实现默认参数的形式
//function calc(x,y){
// x=x||0;
// y=y||0;
// return x+y;
// }
// function calc(x,y){
// if(x===undefined){
// x=0;
// }
// y=y===undefined?0:y;
// return x+y;
// }
// alert(calc());
// alert(calc(1,3));
function calc(x,y){
// return arguments;
//alert(arguments[0]);
//alert(arguments[1]);
x=arguments[0]?arguments[0]:0;
x=arguments[1]?arguments[1]:0;
return x+y;
}
//alert(calc());
// alert(calc(1,2));
//可变参数形式的函数
function test(){
var paramsNum=arguments.length;//得到传入参数的个数
var sum=0;
for(var i=0;i<paramsNum ;++i){
sum+=arguments[i];
}
return sum;
}
//alert(test(1,2,3,4,5,6,7));
function test1(){
var paramsNum=arguments.length;
var max=0;
for(var i=0;i<=paramsNum-1;i++){
if(arguments[i]>max){
max=arguments[i];
}
}
return max;
}
alert(test1(123,4567,177487));
</script>
</body>
</html>