Created
July 5, 2018 19:16
-
-
Save sealocal/9f2e3d03262b1e372d55fa9e43b53de4 to your computer and use it in GitHub Desktop.
Demonstrate private method in JavaScript constructor function.
This file contains hidden or 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
'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