面向对象编程-状态模式(js)

面向对象编程-状态模式(js)

本文参考状态模式(js)


rainbow.prototype.init = function(){
	self = this;
	console.log(this);//<span style="color:#ff0000;">this1</span>
	this.button.οnclick=function(){
		console.log(this);//<span style="color:#ff0000;">this2</span>
		self.currentColor.buttonPress.call(self);
	}
};


在以上代码中this1和this2不是同一个this。this1为rainbow创建的对象,this2为点击事件this.button。所有才有self=this代码。


var rainbow = function(){
	this.currentColor = COLOR.red;
	this.button = document.getElementsByClassName("circle")[0];
};
rainbow.prototype.init = function(c){
	self = this;
	this.button.οnclick=function(){
		self.currentColor.buttonPress.call(self);
	}
};
var COLOR = {
	red:{
		buttonPress:function (){
			document.getElementsByClassName("circle")[0].style.backgroundColor = "orange";
			this.currentColor = COLOR.orange;
		}
	},
	orange:{
		buttonPress:function (){
			document.getElementsByClassName("circle")[0].style.backgroundColor = "yellow";
			this.currentColor = COLOR.yellow;
		}
	},
	yellow:{
		buttonPress:function (){
			document.getElementsByClassName("circle")[0].style.backgroundColor = "red";
			this.currentColor = COLOR.red;
		}
	}
};
new rainbow().init("circle");


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<link rel="stylesheet" href="../css/style.css" />
		<title>状态模式</title>
		<style>
			.circle{
				width:100px;
				height:100px;
				border-radius: 50%;
				background-color: red;
			    margin: 100px auto;
			}
		</style>
	</head>
	<body>
		<div class="return_nav">
			<div class="return_nav_img" onClick="javascript:window.location.href='../index.html'"></div>
			状态模式
		</div>
		<div class="circle" ontouchend=""></div>
	</body>
	<script src="index.js"></script>
</html>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值