Skip to content

Instantly share code, notes, and snippets.

@matthew-carroll
Created June 28, 2014 01:36
Show Gist options
  • Save matthew-carroll/274451ad1f8d330b2623 to your computer and use it in GitHub Desktop.
Save matthew-carroll/274451ad1f8d330b2623 to your computer and use it in GitHub Desktop.
Example of object-oriented programming in JavaScript
// Example of how one might do some object-oriented programming in
// JavaScript. This example uses a prototype definition to present
// a fictional application that might govern a plane taking off
// from an airport. Notice how the program is not just a list of
// instructions - control often leaves the Plane object and then
// later returns to the Plane upon some outside event or message.
// Initiates the take off process
Plane.prototype.takeOff = function() {
this.doSafetyCheck();
if(this.isSafetyVerified()) {
taxiService.requestTaxi(this);
}else{
throw new SafetyException(this.getSafetyViolation());
}
}
// Called when plane has been taxied away from gate
Plane.prototype.onTaxiComplete = function() {
tower.queueForTakeoff(this);
}
// Tells plane when and where to takeoff
Plane.prototype.setTakeoffInstructions = function(time, runway) {
this.runway = runway;
setTimeout(doTakeoff, time);
}
// Called when its time to fly
Plane.prototype.doTakeoff = function() {
this.driveToRunway(this.runway);
if(runway.isClear() && runway.accept(this)) {
this.setHeading(runway.getBearing());
this.pushThrottle(this.throttleCallback);
} else {
runway.onIsClear(this.doTakeoff);
}
}
// Called repeatedly as throttle is pushed forward
Plane.prototype.throttleCallback = function(speed) {
if(speed >= MIN_SPEED_FOR_FLIGHT) {
this.holdThrottle();
this.takeFlight();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment