WeakSet类型的弱引用特点
2020-04-26 本文已影响0人
小雪洁
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>6WeakSet类型的弱引用特点</title>
</head>
<body>
</body>
<script>
//WeakSet类型只有add(),delete(),has()方法
//主要特点就是保存对象数据,即值必须是对象
let hxj={name:"haoxuejie"};
let ws1= new WeakSet();
ws1.add(hxj);
console.log(ws1)//ws1不会为null,但是ws1中已经没有元素了
hxj=null;
console.log(ws1);//ws1引用的对象清空了之后,ws1不会为null,但实际上ws1中已经没有元素了
//WeakSet自以为还有值,如果使用遍历就会报错,
//所以它本身就没有遍历方法,也没有size属性
setTimeout(()=>{
console.log(ws1);
},5000);
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>垃圾回收</title>
</head>
<body>
</body>
<script>
let hxj={name:"haoxuejie",age:31};
let h=hxj;
let arr=[hxj];
console.log(h);//{name: "haoxuejie", age: 31}
console.log(arr);//[{name: "haoxuejie", age: 31}];
hxj=null;//
console.log(hxj);//null
console.log(h);//{name: "haoxuejie", age: 31}这块内存还没有释放
h=null;
console.log(arr);//[{name: "haoxuejie", age: 31}]依旧没有释放,
arr=null;
console.log(arr);//null知道没有元素再引用这块内存了,这块内存就释放了
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8使用WeakSet做一个todolist</title>
</head>
<style>
ul{
list-style-type: none;
width: 100px;
}
ul li{
width:100%;
height: 30px;
border: solid hotpink 2px;
margin: 5px;
display: flex;
justify-content: space-between;
align-items: center;
padding:0 10px;
color:black;
opacity: .8;;
}
ul li a{
text-decoration: none;
font-size: 1.5em;
background: #006699;
height: 80%;
width: 20%;
display: flex;
justify-content: center;
align-items: center;
color: #FFFFFF;
}
.remove{
opacity: .1;
}
</style>
<body>
<ul>
<li>html教程<a href="javascript:;">x</a></li>
<li>css教程<a href="javascript:;">x</a></li>
<li>js教程<a href="javascript:void(0)">x</a></li>
</ul>
</body>
<script>
//定义一个对象
//使用WeakSet存储li节点列表,
//给每个a添加点击事件
class todolist{
constructor(){
this.items=document.querySelectorAll("ul>li");
this.lists=new WeakSet([...this.items]);
//console.log(this.lists);
}
run(){
this.addEvent();
}
addEvent(){
this.items.forEach(item=>{
let a=item.querySelector("a");
a.addEventListener('click',event=>{
const paElem=event.target.parentElement;
if(this.lists.has(paElem)){
paElem.classList.add('remove');
this.lists.delete(paElem);
}else{
paElem.classList.remove('remove');
this.lists.add(paElem);
}
})
})
}
}
new todolist().run();
</script>
</html>
实现效果如下,鼠标点击叉号,清掉list,再次点击再出现:
todolist.gif
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WeakSet的弱引用特性</title>
</head>
<body>
</body>
<script>
let set=new Set();
console.log(set);
//WeakSet没有遍历的方法,比如forEach(),keys()、values()、size等方法
//因为WeakSet的引用它无法判断这个引用地址里面是否已经被系统回收了
let hxj={name:"hxj"};
let ws1=new WeakSet();
ws1.add(hxj);
hxj=null;
console.log(ws1);
let ydc={name:'ydc',age:29};
let ws2=new WeakSet();
ws2=ydc;
//console.log(ws2);
</script>
</html>