您的位置:首页 > Web前端 > JavaScript

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

2018-02-08 20:06 423 查看
什么是闭包?
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息