【JS学习笔记】JS基础下:函数的讲解

晓石头的博客
邮箱:[email protected]
转载请注明出处,原文链接:http://blog.csdn.net/qiulanzhu/article/details/50583667


(function(){
/*两种声明函数的方式*/
	//1、function 函数名(v1, v2, vn){};这种声明的函数可以在其前后使用
	//2、var fn = function(){};这种声明的函数,只能在定义之后使用

	add1(0,1);
	function add1(x, y){
		document.write(x+y +"<br>");
	}
	add1(1,2);
	//add2(2,3);不能在其声明前使用 
	var add2 = function(x, y){
		document.write(x+y +"<br>");
	}	
	add2(3,4);


/*回调函数*/
	function add3(x, y, fn){
		this.x = x||1;
		this.y = y||1;
		if(fn){
			fn(this.x + this.y);
		}
	}
	add3(1,2,function(v){
		if(v>0){
			document.write("value > 0" +"<br>");
		}else{
			document.write("value <= 0" +"<br>");
		}
	})
	
/*函数传参*/
	function add4(x,y,z){
		this.x = x||0;
		this.y = y||0;
		this.z = z||0;
		document.write(this.x + this.y + this.z +"<br>");		
	}
	add4(1,2,3);
	add4(4,5);//弊端:无法像java等高级语言那样有函数精确复写的特性
	
	//技巧:对象传参
	//conf = {gridName:"",gridCode:"",gridSize:""}
	function gridUtil(conf){
		document.write(conf["gridName"] + " " + conf["gridSize"] +"<br>");
	}	
	gridUtil({gridName:"qiuyi", gridCode:"hello", gridSize:"27"});	
	
/*传值还是传址*/
	//1.基础变量是传递数值的
	var i = 100;
	var s = "one";
	
	function add5(i,s){
		i++;
		s = s + "--";
	}
	add5();
	document.write(i +"<br>");
	document.write(s +"<br>");
	
	//2.自定义对象传递的是地址 
	var obj = {name:"qiu"};
	function change(obj){
		obj["name"] = "yi";
	}
	change(obj);
	document.write(obj.name +"<br>");
	
	function recur(start, end){
		var sum = 0;
		sum = sum + start;
		if(start < end){
			sum = sum + recur(start+1, end);
		}
		return sum;
	}
	document.write(recur(1,100) +"<br>");
	
	
/*代理函数:函数生成函数*/
	var person = {"lily":"wenke", "lucy":"like"};
    function test(name){
		if(person[name] == "wenke"){
			return function(lisi, dili){
				document.write(lisi+ " " + dili +"<br>");
			}
		}
		
		if(person[name] == "like"){
			return function(wuli, huaxue){
				document.write(wuli + " " + huaxue +"<br>");
			}
		}
	}
	test("lily")("lishi.", "dili.");
	test("lucy")("wuli.", "huaxue.");
	
/*eval的应用*/
	//eval:把一个字符串解析成一个方法并调用
	var str = "var show = (function(){document.write(100)})()";
	eval(str);
	document.write("<br>");
	//用于数据库返回一个字符串(格式同javascrip数组)
	var data = "[1,2,3,4,5]";
	var array = eval(data);
	for(i = 0; i < array.length; i++){
		document.write(array[i] + " ");
	}
	
	
	
	
	
	
	
})()






你可能感兴趣的:(JavaScript,函数)