ES6 構造函數
- ES6構造函數
//es6_構造函數
class Cat{
constructor(name,age){
this.name=name || '小貓'; //默認值 ‘小貓’
this.age=age | 1; //默認值 1
this.jiao()
}
jiao(){
console.log(this)
console.log(this.name+'喵~~喵~~喵~~喵')
}
}
let a=new Cat('hahah',12);
例題
開關
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.switch {
width: 80px;
height: 40px;
border-radius: 20px;
background: gray;
position: relative;
}
.switch .button {
width: 40px;
height: 40px;
border-radius: 50%;
background: green;
position: absolute;
left: 0;
transition: left 0.6s;
}
.switch.off .button {
left: 0;
}
.switch.on {
background: purple;
}
.switch.on .button {
left: 40px;
}
</style>
</head>
<body>
<ul>
<li><span>WIFI</span><span class="box"></span></li>
<li><span>搖一搖</span><span class="box"></span></li>
<li><span>附近的人</span><span class="box"></span></li>
</ul>
<script>
class Switch {
constructor(el) {
this.el = el;
this.muBan = `
<div class='switch off'>
<div class='button'></div>
</div>
`
this.isOff=true
this.el.innerHTML=this.muBan
this.KaiGuan=this.el.querySelector('.switch')
this.bindEvent()
// console.log(this.KaiGuan)
}
bindEvent(){
this.KaiGuan.onmousedown=()=>{
if(this.isOff){
this.on()
console.log('on')
}else{
this.off()
console.log('off')
}
this.isOff=!this.isOff
}
}
on(){
this.KaiGuan.classList.remove('off')
this.KaiGuan.classList.add('on')
}
off(){
this.KaiGuan.classList.remove('on')
this.KaiGuan.classList.add('off')
}
}
let boxs = document.querySelectorAll('.box')
for (let i = 0; i < boxs.length; i++) {
new Switch(boxs[i]);
}
</script>
</body>
</html>