- The following state machine chooses to delegate the request directly to a literal object through the Function.prototype.call method.
varLight =function () { This. currstate =Fsm.off; This. Button =NULL; }; Light.prototype.init=function () { varbutton = document.createelement (' button '); Self= This; Button.innerhtml= ' Lights off '; This. Button =document.body.appendChild (button); This. Button.onclick =function() {self.currstate.buttonWasPressed.call (self); }; }; varFSM ={off: {buttonwaspressed:function() {Console.log (' Turn off the lights '); This. button.innerhtml = ' next time I turn on the light '; This. currstate =Fsm.on; }}, on: {buttonwaspressed:function() {Console.log (' Turn on the Light '); This. button.innerhtml = ' next time press I'm turning off the lights '; This. currstate =Fsm.off; } } }; varLight =NewLight (); Light.init ();
- The following uses the delegate function to rewrite the state machine again
- This is an example of object-oriented and closure swaps. The former saves the variable as a property of the object, which encloses the variable in the environment in which the closure is formed :
varDelegate =function(client, delegation) {return{buttonwaspressed:function () { returndelegation.buttonWasPressed.apply (client, arguments); } }; }; varLight =function () { This. Offstate = Delegate ( This, Fsm.off); This. Onstate = Delegate ( This, Fsm.on); This. currstate =Fsm.off; This. Button =NULL; }; Light.prototype.init=function () { varbutton = document.createelement (' button '); Self= This; Button.innerhtml= ' Lights off '; This. Button =document.body.appendChild (button); This. Button.onclick =function() {self.currstate.buttonWasPressed.call (self); }; }; varFSM ={off: {buttonwaspressed:function() {Console.log (' Turn off the lights '); This. button.innerhtml = ' next time I turn on the light '; This. currstate = This. onstate; }}, on: {buttonwaspressed:function() {Console.log (' Turn on the Light '); This. button.innerhtml = ' next time press I'm turning off the lights '; This. currstate = This. offstate; } } }; varLight =NewLight (); Light.init ();
JS Mode-state mode (state machine)