Skip to content

Instantly share code, notes, and snippets.

@sealocal
Created July 5, 2018 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sealocal/9f2e3d03262b1e372d55fa9e43b53de4 to your computer and use it in GitHub Desktop.
Save sealocal/9f2e3d03262b1e372d55fa9e43b53de4 to your computer and use it in GitHub Desktop.
Demonstrate private method in JavaScript constructor function.
'use strict'
function Car(make, model, year) {
// public variables
this.make = make;
this.model = model;
this.year = year;
this.breakPedalIsPressed = false;
// private variable
var engineStartAttempts = 0;
this.startEngine = function() {
if (checkStartEngineRequirements()) {
console.log('Engine started!')
return true;
} else { // failed requirements
console.log('Engine start failed!')
return false
}
}
// public method, accesses public variable
this.pressBreakPedal = function() {
this.breakPedalIsPressed = true;
}
// public method, accesses public variable
this.releaseBreakPedal = function() {
this.breakPedalIsPressed = false;
}
// private methods
var thisCar = this;
// private method, accesses private variable
var checkStartEngineRequirements = function() {
console.log('engineStartAttempts: ', ++engineStartAttempts)
return ensureBreakPedalIsPressed();
}
// private method, accesses public variable
var ensureBreakPedalIsPressed = function() {
thisCar.breakPedalIsPressed ? true : console.log('Break pedal is not pressed.')
return thisCar.breakPedalIsPressed;
}
}
let car = new Car('Tesla', 'Model 4', 2021);
console.log('\n')
// start the car with a failed start, then a success start.
console.log(car.startEngine())
console.log(car.pressBreakPedal())
console.log(car.startEngine())
console.log(car.releaseBreakPedal())
console.log('\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment