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

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

本文参考状态模式(js)


rainbow.prototype.init = function(){
	self = this;
	console.log(this);//this1
	this.button.οnclick=function(){
		console.log(this);//this2
		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");




	
		
		
		
		状态模式
		
	
	
		
状态模式


你可能感兴趣的:(javascript)