现在的位置: 首页 > 综合 > 正文

JavaScript 函数

2018年02月04日 ⁄ 综合 ⁄ 共 1600字 ⁄ 字号 评论关闭
文章目录

函数(function)

函数是一个可执行的javascript代码段,有javascript程序定义或由javascript实现预定义。

函数名

相同的函数名称只能定义一次(相同的函数名称会存在覆盖的问题)

<html>
	<head>
		<title>function</title>
	</head>
	<body>
		<input type="button" value="click" onclick="test();">
		
		<script>
			function test(){
				alert('a');
			}
			function test(t){
				alert('b');
			}
		</script>
	</body>
</html>

结果:是“b”

函数参数

 javascript 函数可以以任意数目的参数来调用,而不管函数定义中的参数名字有多少个。

<html>
	<head>
		
	</head>
	<body>
		<script type="text/javascript">
		function test(a, b, c, d){
			alert(a + b + c + d);
		}
		test(1,2,3,4,5,6);//10
		
		function test1(a, b, c, d){
			alert(a);//1
			alert(b);//undefind
			alert(c);//undefind
			alert(d);//undefind
		}
		test1(1);
		</script>
	</body>
</html>

可变长度的参数列表:Arguments 对象

每一个函数都有一个arguments属性。arguments是一个对象,具有length属性。arguments存储的是调用函数的参数,可以使用arguments[index] 来改变传入参数的值。

<html>
	<head>
		
	</head>
	<body>
		<script type="text/javascript">
		function test(a, b, c, d){
			if (arguments.length != 4){
				throw new Error("function test called with arguments less than 4 arguments length:" + arguments.length);
			}
		}
		test();//arguments.length是0
		</script>
	</body>
</html>

注意:由于javascript 函数是不会对参数检查的,有必要的还是先要判断一下。

函数的属性和方法

属性:length 是函数的参数的个数

<html>
	<head>
		
	</head>
	<body>
		<script type="text/javascript">
		function check(args){
			var actual = args.length;
			alert(actual);//4
			var expected = args.callee.length;
			alert(expected);//3
		}
		
		function f(x,y,z){
			check(arguments);
			alert(x+y+z);
		}
		
		f(1,2,3,4);
		</script>
	</body>
</html>

属性:prototype

// TODO

自定义属性:函数需要使用一个在调用过程中都保持不点的值,可以使用自定义属性(或者使用全局变量)

<html>
	<head>
		
	</head>
	<body>
		<script type="text/javascript">
		check.counter = 0;
		function check(){
			alert(check.counter++);
		}
		
		for (var i=0;i<2;i++){
			check();//0,1
		}
		</script>
	</body>
</html>

方法:call() 和 apply() 方法第一个参数都是要调用的函数对象,call 方法剩余的参数是传递给调用的函数的值。apply 方法要传递给函数的参数是由数组指定的

函数的作用域和闭包

 // TODO

 

 

 

 

 

 

 

 

 

 

 

 

 

抱歉!评论已关闭.