上升到面向对象:定义不同的类,让类的实例工作
在这里插入代码片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js面向对象——红绿灯实例</title>
<style>
img {
width: 70px;
height: 150px;
}
</style>
</head>
<body>
<!-- 上升到面向对象:定义类,让类的实例工作 -->
<div id="box"></div>
<script>
// 定义红绿灯类
function TrafficLight() {
// 定义红绿灯颜色 红1黄2绿3
this.color = 1
// 调用自己的初始化函数
this.init()
// 调用自己的绑定事件
this.bindEvent()
}
var box = document.getElementById('box')
// 添加初始化函数init()
TrafficLight.prototype.init = function () {
// 创建自己的dom
this.dom = document.createElement('img')
// 设置dom内容
this.dom.src = 'images/' + this.color + '.jpg'
// 添加dom至网页
box.appendChild(this.dom)
}
// 绑定事件
TrafficLight.prototype.bindEvent = function () {
// 注意:需要备份上下文,因为this.bindEvent()中this-t1对象,而this.dom.onclick处理函数中的this指的是dom元素
var _this = this
// 点击dom元素,自己的颜色变化
this.dom.onclick = function () {
// 当被点击时,调用对象的changeColor方法
_this.changeColor()
}
}
TrafficLight.prototype.changeColor = function () {
// 点击dom元素,该对象的color发生变化
this.color++
// 当_this.color为4时,令其等于1
if (this.color == 4) {
this.color = 1
}
this.dom.src = 'images/' + this.color + '.jpg'
}
// 创建多个红绿灯
var num = 3
while (num--)[
new TrafficLight()
]
</script>
</body>
</html>