面向对象编程-状态模式(js)
2016-02-24 15:10
771 查看
面向对象编程-状态模式(js)
本文参考状态模式(js)
在以上代码中this1和this2不是同一个this。this1为rainbow创建的对象,this2为点击事件this.button。所有才有self=this代码。
本文参考状态模式(js)
rainbow.prototype.init = function(){ self = this; console.log(this);//<span style="color:#ff0000;">this1</span> this.button.onclick=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.onclick=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>
相关文章推荐
- Js基础二(字面量、typeof、所类型的boolean值)
- JavaScript开发整理
- javascript随机数生成公式
- javascript cookie的简单应用
- javascript字符串截取
- js 创建对象的几种方式
- html+css+JavaScript贪吃蛇
- js 创建<a>标签 并触发
- javascript的正则匹配方法学习
- web学习-jsp
- Volley扩展-json上传,json字符串解析
- JavaScript基础知识1
- ajax请求返回json字符串/json对象 处理
- Jsp开发整理
- JavaScript学习笔记(2)——JavaScript和DOM的关系
- Javascript 判断浏览器是否为IE的最短方法
- JavaScript作用域学习笔记
- JavaScript之IE的fireEvent方法详细解析
- 适用于javascript开发者的Processing.js入门教程
- JSP页面中 <base href="<%=basePath%>">