<!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>
</head>
<body>
<script>
var StrongLight = function(light) {
this.light = light;
}
StrongLight.prototype.btnPress = function() {
console.log("弱光");
this.light.dom.innerHTML = '燈狀態:弱光';
this.light.setState(this.light.weakLight);
}
var WeakLight = function(light) {
this.light = light;
}
WeakLight.prototype.btnPress = function() {
console.log("關閉");
this.light.dom.innerHTML = '燈狀態:關閉';
this.light.setState(this.light.offLight);
}
var OffLight = function(light) {
this.light = light;
}
OffLight.prototype.btnPress = function() {
console.log("強光");
this.light.dom.innerHTML = '燈狀態:強光';
this.light.setState(this.light.strongLight);
}
var Light = function() {
this.strongLight = new StrongLight(this);
this.weakLight = new WeakLight(this);
this.offLight = new OffLight(this);
this.dom = null;
this.button = null;
}
Light.prototype.init = function() {
var button = document.createElement('button');
var dom = document.createElement('div');
var _self = this;
button.innerHTML = "開關";
dom.innerHTML = "燈狀態:關閉";
_self.dom = dom;
_self.state = this.offLight;
document.body.append(dom);
document.body.append(button);
button.onclick = function() {
_self.state.btnPress();
}
}
Light.prototype.setState = function(state) {
this.state = state;
}
var light = new Light();
light.init();
</script>
</body>
</html>複製代碼