Last active
August 29, 2015 14:13
-
-
Save gregtatum/4a1de888bc5c603e0754 to your computer and use it in GitHub Desktop.
Storing State in Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Typical prototypical pattern. Store all state, configuration, and functions on the "this" object. | |
*/ | |
var Car = function( engineType ) { | |
this.engine = engineType || "v4"; | |
this.timesRevved = 0; | |
}; | |
Car.prototype = { | |
rev : function() { | |
this.timesRevved++; | |
switch( this.engine ) { | |
case "v8": | |
console.log("vrooooooooom!"); | |
break; | |
case "v6": | |
console.log("vroooom"); | |
break; | |
default: | |
console.log("vroom"); | |
} | |
} | |
}; | |
var car = new Car( "v8" ); | |
car.rev(); | |
//Mutate | |
car.engine = "v6"; | |
car.rev(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function engineRever() { | |
this.state.timesRevved++; | |
switch( this.engine ) { | |
case "v8": | |
console.log("vrooooooooom!"); | |
break; | |
case "v6": | |
console.log("vroooom"); | |
break; | |
default: | |
console.log("vroom"); | |
} | |
} | |
var car = function( privateEngine ) { | |
var state = { | |
timesRevved: 0 | |
}; | |
return { | |
rev : engineRever.bind({ | |
engine : privateEngine, | |
state : state | |
}), | |
timesRevved : function() { return state.timesRevved } | |
}; | |
}; | |
var normalCar = car( "v6" ); | |
normalCar.rev(); | |
var fastCar = car( "v8" ); | |
fastCar.rev(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function engineRever( state, engine ) { | |
state.timesRevved++; | |
return function rev() { | |
switch( engine ) { | |
case "v8": | |
console.log("vrooooooooom!"); | |
break; | |
case "v6": | |
console.log("vroooom"); | |
break; | |
default: | |
console.log("vroom"); | |
} | |
} | |
} | |
var car = function( engine ) { | |
var state = { | |
timesRevved: 0 | |
}; | |
return { | |
rev : engineRever( state, engine ), | |
timesRevved : function() { return state.timesRevved } | |
}; | |
}; | |
var normalCar = car( "v6" ); | |
console.log( normalCar.timesRevved() ); | |
normalCar.rev(); | |
console.log( normalCar.timesRevved() ); | |
var fastCar = car( "v8" ); | |
fastCar.rev(); | |
fastCar.rev(); | |
console.log( fastCar.timesRevved() ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment