/** * Created by kikop on 2018/3/29. */ //1.单例模式的红绿灯对象 //实现思路: function 函数表达式,() 立即执行 var trafficLight = (function () { //1.私有变量(如果想对象拥有,则放构造函数里面;如果想单例特性,则放prototype里面即可) var currentLight = null; var tmpLight=null; //2.全局函数 globalDisPlayLight=function (){ currentLight.go(); } //3.私有函数 var _displayLight=function(){ currentLight.go(); } //4.不推荐使用,不加var,这个变量是全局的 globalLight = null; //5.暴露给外部的方法,通过对象字面量返回 return { setLight: function (light) { currentLight = light; }, getLight: function () { return currentLight; }, execute: function () { //1.调用内部共有函数 //this.getLight().go(); //2.调用全局共有函数 //globalDisPlayLight(); //3.调用私有函数 _displayLight(); }, change: function (light) { tmpLight = light; tmpLight.go(); } } })(); //2.具体对象 function RedLight() { this.name="obj define"; } RedLight.prototype.name='rototype define'; RedLight.prototype.go = function () { console.log('this is red light.'); } RedLight.prototype.displayName = function () { //执行顺序:对象-->原型 console.log('displayName:'+this.name); } function GreenLight() { } GreenLight.prototype.go = function () { console.log('this is green light.'); } //3.测试 var redLight = new RedLight(); redLight.displayName(); trafficLight.change(redLight); var greenLight = new GreenLight(); trafficLight.setLight(redLight); trafficLight.setLight(greenLight); trafficLight.execute();