Skip to content

Instantly share code, notes, and snippets.

@gregtatum
Last active August 29, 2015 14:13
Show Gist options
  • Save gregtatum/4a1de888bc5c603e0754 to your computer and use it in GitHub Desktop.
Save gregtatum/4a1de888bc5c603e0754 to your computer and use it in GitHub Desktop.
Storing State in Functions
/*
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();
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();
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