js闭包的定义与应用+获取元素下标的多种方法

什么是闭包?

closure,函数嵌套函数,内层函数有使用到外层函数所定义的变量,外层函数返回对内层函数的引用;

用途:希望在函数外部能够使用到函数内部所定义的局部变量(延长变量的生命周期),可以使用闭包;

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
<style type="text/css">
	ul li{
		width: 200px;
		height: 50px;
		background: #ccc;
		margin-bottom: 5px;
	}
</style>
</head>
<body>
	<ul>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
		<li></li>
	</ul>
<script type="text/javascript">
	// 闭包应用之一(获取元素下标 ps:这种方法麻烦,实际需要直接用let变量或者自定义属性方法)
	var lis = document.getElementsByTagName("ul")[0].getElementsByTagName("li");
	for(var i = 0; i < lis.length; i++){
		lis[i].onclick = clk(i);
	}
	function clk(index){
		return function(){
			for(var i = 0; i < lis.length; i++)
				lis[i].style.background = "#ccc";
			lis[index].style.background = "red";
		}
	}
	
 /*利用循环体嵌套IIFE获取下标*/
    // for(var i = 0; i < lis.length; i++){
    // 	(function(li, index){
    // 		li.onclick = function(){
    // 			console.log(index);
    // 		}
    // 	}(lis[i], i))
    // }
 /*利用数组forEach方法实现获取下标([].slice.call(lis)等同于ES6的Array.from(lis))*/
    // [].slice.call(lis).forEach(function(li, index){
    // 	li.onclick = function(){
    // 		console.log(index);
    // 	}
    // })

// 闭包应用之二(对象私有属性)
	function Doubi(name, sex, level){
		this.name = name;
		this.sex = sex;
		var arg;
		this.setLevel = (v) => arg = v >= 0 ? v : level;
		this.getLevel = () => arg;
	}
	var dbObj = new Doubi("何亮", "男", 0);
	dbObj.setLevel(50);
	console.log(dbObj.getLevel());
// 闭包应用之三(结合IIFE减少全局变量污染)
	(function(){
		function Random(){
			this.randomNum=(m, b) => Math.floor(Math.random() * (b - m + 1)+ m); 
			this.randomRgb=() => "rgb("+this.randomNum(0, 255)+","+this.randomNum(0, 255)+","+this.randomNum(0, 255)+")"; 
		}
		function haha(){
			console.log("haha");
		}
		var tool = {
			Random : new Random(),
			haha
		}
		window.tool = tool;
	}());
	console.log(tool.Random.randomRgb());
</script>
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值